Skip to content

Commit 2821b32

Browse files
committed
maximum-subarray solution
1 parent f3179e9 commit 2821b32

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

โ€Žmaximum-subarray/togo26.jsโ€Ž

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
// TLE
7+
// var maxSubArray = function(nums) {
8+
// if (nums.length <= 1) return nums[0];
9+
10+
// const sum = (arr) => arr.reduce((acc, cur) => {
11+
// acc += cur;
12+
// return acc;
13+
// }, 0);
14+
15+
// let total = -Infinity;
16+
// for (let i = 0; i < nums.length; i++) {
17+
// for (let j = i; j < nums.length; j++) {
18+
// const result = sum(nums.slice(i, j + 1));
19+
// total = Math.max(total, result);
20+
// }
21+
// }
22+
23+
// return total;
24+
// };
25+
26+
// TLE
27+
// var maxSubArray = function(nums) {
28+
// if (nums.length <= 1) return nums[0];
29+
30+
// let total = -Infinity;
31+
// for (let i = 0; i < nums.length; i++) {
32+
// let acc = 0;
33+
// for (let j = i; j < nums.length; j++) {
34+
// acc += nums[j];
35+
// total = Math.max(total, acc);
36+
// }
37+
// }
38+
39+
// return total;
40+
// };
41+
42+
// TC: O(n) / SC: O(1)
43+
var maxSubArray = function (nums) {
44+
let total = nums[0];
45+
let acc = nums[0];
46+
47+
for (let i = 1; i < nums.length; i++) {
48+
acc = Math.max(nums[i], acc + nums[i]); // ์ด์ „ ๋ˆ„์ ๊ฐ’ ์„ ํƒ vs ํ˜„์žฌ๊ฐ’ ์„ ํƒ (์นด๋ฐ์ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜)
49+
total = Math.max(total, acc); // ์ตœ๋Œ€ ํ•ฉ์‚ฐ ๊ฐ’ ๊ฐฑ์‹ 
50+
}
51+
52+
return total;
53+
};

0 commit comments

Comments
ย (0)