File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ } ;
You canโt perform that action at this time.
0 commit comments