File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ var rob = function ( nums ) {
5
+ // to rob a linear list of houses
6
+ function robLinear ( houses ) {
7
+ let prev1 = 0 ;
8
+ let prev2 = 0 ;
9
+
10
+ for ( let money of houses ) {
11
+ let temp = Math . max ( prev1 , money + prev2 ) ;
12
+ prev2 = prev1 ;
13
+ prev1 = temp ;
14
+ }
15
+
16
+ return prev1 ;
17
+ }
18
+
19
+ // 1. excluding the last house (rob from first to second-to-last)
20
+ // 2. excluding the first house (rob from second to last)
21
+ let robFirstToSecondLast = robLinear ( nums . slice ( 0 , - 1 ) ) ;
22
+ let robSecondToLast = robLinear ( nums . slice ( 1 ) ) ;
23
+
24
+ // return the maximum money
25
+ return Math . max ( robFirstToSecondLast , robSecondToLast ) ;
26
+ } ;
Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ var rob = function ( nums ) {
5
+ // to store the maximum money that can be robbed up to each house
6
+ let memo = new Array ( nums . length ) . fill ( - 1 ) ;
7
+
8
+ function robFrom ( i ) {
9
+ // if the index is out of bounds, return 0
10
+ if ( i >= nums . length ) return 0 ;
11
+
12
+ // 1. rob this house and move to the house two steps ahead
13
+ // 2. skip this house and move to the next house
14
+ // take the maximum of these two choices
15
+ let result = Math . max ( nums [ i ] + robFrom ( i + 2 ) , robFrom ( i + 1 ) ) ;
16
+
17
+ // store the result
18
+ memo [ i ] = result ;
19
+
20
+ return result ;
21
+ }
22
+
23
+ // start robbing from the first house
24
+ return robFrom ( 0 ) ;
25
+ } ;
You can’t perform that action at this time.
0 commit comments