Skip to content

Commit 777ffec

Browse files
committed
4. Maximum Subarray
1 parent bc4e7e5 commit 777ffec

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

maximum-subarray/sunjae95.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @description
3+
* n = length of nums
4+
* time complexity: O(n)
5+
* space complexity: O(1)
6+
*/
7+
var maxSubArray = function (nums) {
8+
let sum = 0;
9+
let answer = nums[0];
10+
11+
for (let end = 0; end < nums.length; end++) {
12+
if (sum < 0) {
13+
sum = nums[end];
14+
} else if (sum + nums[end] >= 0) {
15+
sum += nums[end];
16+
} else {
17+
sum = nums[end];
18+
}
19+
20+
answer = Math.max(answer, sum);
21+
}
22+
return answer;
23+
};

0 commit comments

Comments
 (0)