File tree Expand file tree Collapse file tree 1 file changed +9
-8
lines changed Expand file tree Collapse file tree 1 file changed +9
-8
lines changed Original file line number Diff line number Diff line change @@ -11,14 +11,15 @@ function rob(nums: number[]): number {
11
11
if ( nums . length === 1 ) return nums [ 0 ] ;
12
12
if ( nums . length === 2 ) return Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
13
13
14
- const dp : number [ ] = new Array ( nums . length ) ;
15
-
16
- dp [ 0 ] = nums [ 0 ] ;
17
- dp [ 1 ] = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
14
+ let prev = nums [ 0 ] ;
15
+ let maxResult = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
16
+ let current = 0 ;
18
17
19
18
// λ¨μ μ§μ μννλ©΄μ μ΅λκ°μ ꡬν¨
20
- for ( let i = 2 ; i < nums . length ; i ++ )
21
- dp [ i ] = Math . max ( dp [ i - 1 ] , dp [ i - 2 ] + nums [ i ] ) ;
22
-
23
- return dp [ nums . length - 1 ] ;
19
+ for ( let i = 2 ; i < nums . length ; i ++ ) {
20
+ current = Math . max ( maxResult , prev + nums [ i ] ) ;
21
+ prev = maxResult ;
22
+ maxResult = current ;
23
+ }
24
+ return maxResult ;
24
25
}
You canβt perform that action at this time.
0 commit comments