File tree Expand file tree Collapse file tree 1 file changed +12
-5
lines changed
Expand file tree Collapse file tree 1 file changed +12
-5
lines changed Original file line number Diff line number Diff line change 11// Time complexity: O(n)
2- // Space complexity: O(n )
2+ // Space complexity: O(1 )
33
44/**
55 * @param {number[] } nums
66 * @return {number }
77 */
88var maxSubArray = function ( nums ) {
99 const n = nums . length ;
10- const dp = Array . from ( { length : n + 1 } , ( ) => Number . MIN_SAFE_INTEGER ) ;
11- dp [ 0 ] = 0 ;
10+ const dp = [ 0 , 0 ] ;
11+
12+ let answer = Number . MIN_SAFE_INTEGER ;
1213
1314 for ( let i = 1 ; i <= n ; i ++ ) {
14- dp [ i ] = Math . max ( dp [ i - 1 ] + nums [ i - 1 ] , nums [ i - 1 ] ) ;
15+ if ( i % 2 !== 0 ) {
16+ dp [ 1 ] = Math . max ( dp [ 0 ] + nums [ i - 1 ] , nums [ i - 1 ] ) ;
17+ answer = Math . max ( answer , dp [ 1 ] ) ;
18+ } else {
19+ dp [ 0 ] = Math . max ( dp [ 1 ] + nums [ i - 1 ] , nums [ i - 1 ] ) ;
20+ answer = Math . max ( answer , dp [ 0 ] ) ;
21+ }
1522 }
1623
17- return Math . max ( ... dp . slice ( 1 ) ) ;
24+ return answer ;
1825} ;
You can’t perform that action at this time.
0 commit comments