Skip to content

Commit 54d1bcf

Browse files
committed
Add maximum-subarray solution
1 parent 4fa6523 commit 54d1bcf

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

maximum-subarray/Jeehay28.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
// Dynamic programming
7+
8+
9+
// Optimized Solution:
10+
// Time Complexity: O(n)
11+
// Space Complexity: O(1)
12+
13+
14+
var maxSubArray = function (nums) {
15+
16+
let currentMax = nums[0];
17+
let globalMax = nums[0]
18+
19+
for (let i = 1; i < nums.length; i++) {
20+
21+
currentMax = Math.max(currentMax + nums[i], nums[i]);
22+
globalMax = Math.max(currentMax, globalMax);
23+
24+
}
25+
26+
return globalMax;
27+
28+
};
29+
30+
31+
// Time Complexity: O(n)
32+
// Space Complexity: O(n)
33+
34+
// var maxSubArray = function (nums) {
35+
36+
// let dp = [nums[0]];
37+
38+
// for (let i = 1; i < nums.length; i++) {
39+
40+
// dp[i] = Math.max(dp[i - 1] + nums[i], nums[i])
41+
42+
// }
43+
44+
// return Math.max(...dp)
45+
46+
// };

0 commit comments

Comments
 (0)