Skip to content

Commit fc25046

Browse files
committed
max subarray
1 parent 417109e commit fc25046

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

maximum-subarray/nowrobin.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var maxSubArray = function(nums) {
6+
if (!nums || nums.length === 0) {
7+
return 0;
8+
}
9+
10+
// max_so_far: overall maximum sum
11+
let max_so_far = nums[0];
12+
13+
// max_ending_here: max sum of subarray ending at current position
14+
let max_ending_here = nums[0];
15+
16+
for (let i = 1; i < nums.length; i++) {
17+
// Core decision: start new or extend previous
18+
max_ending_here = Math.max(nums[i], max_ending_here + nums[i]);
19+
20+
// Update overall maximum
21+
max_so_far = Math.max(max_so_far, max_ending_here);
22+
}
23+
24+
return max_so_far;
25+
};

0 commit comments

Comments
 (0)