Skip to content

Commit b33c711

Browse files
committed
Add solution #1031
1 parent f94b387 commit b33c711

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,102 LeetCode solutions in JavaScript
1+
# 1,103 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -838,6 +838,7 @@
838838
1028|[Recover a Tree From Preorder Traversal](./solutions/1028-recover-a-tree-from-preorder-traversal.js)|Hard|
839839
1029|[Two City Scheduling](./solutions/1029-two-city-scheduling.js)|Medium|
840840
1030|[Matrix Cells in Distance Order](./solutions/1030-matrix-cells-in-distance-order.js)|Easy|
841+
1031|[Maximum Sum of Two Non-Overlapping Subarrays](./solutions/1031-maximum-sum-of-two-non-overlapping-subarrays.js)|Medium|
841842
1037|[Valid Boomerang](./solutions/1037-valid-boomerang.js)|Easy|
842843
1038|[Binary Search Tree to Greater Sum Tree](./solutions/1038-binary-search-tree-to-greater-sum-tree.js)|Medium|
843844
1041|[Robot Bounded In Circle](./solutions/1041-robot-bounded-in-circle.js)|Medium|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 1031. Maximum Sum of Two Non-Overlapping Subarrays
3+
* https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums and two integers firstLen and secondLen, return the maximum sum
7+
* of elements in two non-overlapping subarrays with lengths firstLen and secondLen.
8+
*
9+
* The array with length firstLen could occur before or after the array with length secondLen,
10+
* but they have to be non-overlapping.
11+
*
12+
* A subarray is a contiguous part of an array.
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @param {number} firstLen
18+
* @param {number} secondLen
19+
* @return {number}
20+
*/
21+
var maxSumTwoNoOverlap = function(nums, firstLen, secondLen) {
22+
const prefixSums = getPrefixSums(nums);
23+
let maxFirst = 0;
24+
let maxSecond = 0;
25+
let result = 0;
26+
27+
for (let i = firstLen; i <= nums.length - secondLen; i++) {
28+
maxFirst = Math.max(maxFirst, prefixSums[i] - prefixSums[i - firstLen]);
29+
const secondSum = prefixSums[i + secondLen] - prefixSums[i];
30+
result = Math.max(result, maxFirst + secondSum);
31+
}
32+
33+
for (let i = secondLen; i <= nums.length - firstLen; i++) {
34+
maxSecond = Math.max(maxSecond, prefixSums[i] - prefixSums[i - secondLen]);
35+
const firstSum = prefixSums[i + firstLen] - prefixSums[i];
36+
result = Math.max(result, maxSecond + firstSum);
37+
}
38+
39+
return result;
40+
41+
function getPrefixSums(arr) {
42+
const sums = [0];
43+
for (let i = 0; i < arr.length; i++) {
44+
sums.push(sums[i] + arr[i]);
45+
}
46+
return sums;
47+
}
48+
};

0 commit comments

Comments
 (0)