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