File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://leetcode.com/problems/maximum-subarray/
2+
3+ // Time Limit Exceeded
4+ function maxSubArray ( nums : number [ ] ) : number {
5+ const acc = [ ]
6+ const len = nums . length
7+
8+ for ( let size = 1 ; size <= len ; size ++ ) {
9+ for ( let start = 0 ; start <= len - size ; start ++ ) {
10+ const sub = nums . slice ( start , start + size )
11+ const sum = sub . reduce ( ( acc , num ) => acc += num , 0 )
12+ acc . push ( sum )
13+ }
14+ }
15+
16+ return acc . sort ( ( a , b ) => b - a ) [ 0 ]
17+ } ;
18+
19+ // TC: O(n)
20+ // SC: O(n)
21+
22+ function maxSubArray ( nums : number [ ] ) : number {
23+ const dp = [ ...nums ] ;
24+ let max = dp [ 0 ] ;
25+
26+ for ( let i = 1 ; i < nums . length ; i ++ ) {
27+ dp [ i ] = Math . max ( nums [ i ] , dp [ i - 1 ] + nums [ i ] ) ;
28+ max = Math . max ( max , dp [ i ] ) ;
29+ }
30+
31+ return max ;
32+ }
You can’t perform that action at this time.
0 commit comments