File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * time complexity: O(n) - iterate over a loop
3
+ * space complexity: O(n) - dp array
4
+ *
5
+ * comment: initial naive implementation: simple odd/even alternation, which may return result that is "accidentally correct."
6
+ */
7
+ function rob ( nums : number [ ] ) : number {
8
+ // early return
9
+ if ( nums . length === 0 ) return 0 ;
10
+ if ( nums . length === 1 ) return nums [ 0 ] ;
11
+
12
+ const dp : number [ ] = new Array ( nums . length ) ;
13
+ dp [ 0 ] = nums [ 0 ] ;
14
+ dp [ 1 ] = Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
15
+
16
+ for ( let i = 2 ; i < nums . length ; i ++ ) {
17
+ // select either 1) current + best from 2 houses ago or 2) skip current, best from previous
18
+ dp [ i ] = Math . max ( nums [ i ] + dp [ i - 2 ] , dp [ i - 1 ] ) ;
19
+ }
20
+
21
+ return dp [ nums . length - 1 ] ; // max money from all houses
22
+ }
You can’t perform that action at this time.
0 commit comments