Skip to content

Commit 78b951e

Browse files
authored
Update 53-maximum-subarray.js
1 parent e7e446d commit 78b951e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

53-maximum-subarray.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,33 @@ const maxSubArray = function(nums) {
1111
}
1212
return maxSum;
1313
};
14+
15+
// another
16+
17+
/**
18+
* @param {number[]} nums
19+
* @return {number}
20+
*/
21+
const maxSubArray = function(nums) {
22+
return helper(nums, 0, nums.length - 1)
23+
};
24+
25+
function helper(arr, l, r) {
26+
if(l > r) return -Infinity
27+
const mid = l + ((r - l) >> 1)
28+
let cur = 0, leftMax = 0, rightMax = 0
29+
for(let i = mid - 1; i >= l; i--) {
30+
cur += arr[i]
31+
leftMax = Math.max(leftMax, cur)
32+
}
33+
cur = 0
34+
for(let i = mid + 1; i <= r; i++) {
35+
cur += arr[i]
36+
rightMax = Math.max(rightMax, cur)
37+
}
38+
const res = arr[mid] + leftMax + rightMax
39+
const leftRes = helper(arr, l, mid - 1)
40+
const rightRes = helper(arr, mid + 1, r)
41+
42+
return Math.max(res, leftRes, rightRes)
43+
}

0 commit comments

Comments
 (0)