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 1
1
// Time complexity: O(n)
2
- // Space complexity: O(n )
2
+ // Space complexity: O(1 )
3
3
4
4
/**
5
5
* @param {number[] } nums
6
6
* @return {number }
7
7
*/
8
8
var maxSubArray = function ( nums ) {
9
9
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 ;
12
13
13
14
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
+ }
15
22
}
16
23
17
- return Math . max ( ... dp . slice ( 1 ) ) ;
24
+ return answer ;
18
25
} ;
You can’t perform that action at this time.
0 commit comments