File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ // ✅ Time Complexity: O(n)
2+ // ✅ Space Complexity: O(1)
3+
4+ /**
5+ * @param {number[] } nums
6+ * @return {number }
7+ */
8+ var rob = function ( nums ) {
9+ // Edge case: If there's only one house, return its value
10+ if ( nums . length === 1 ) return nums [ 0 ] ;
11+
12+ // helper function
13+ const robHouses = ( start , end ) => {
14+ // prev1: stores the maximum money robbed up to the previous house.
15+ // prev2: stores the maximum money robbed up to the house before the previous house.
16+ let prev1 = 0 ,
17+ prev2 = 0 ;
18+
19+ for ( let i = start ; i <= end ; i ++ ) {
20+ let temp = Math . max ( prev1 , prev2 + nums [ i ] ) ;
21+
22+ prev2 = prev1 ;
23+
24+ prev1 = temp ;
25+ }
26+
27+ return prev1 ;
28+ } ;
29+
30+ // Excluding the last house: robHouses(0, nums.length - 2)
31+ // Excluding the first house: robHouses(1, nums.length - 1)
32+
33+ return Math . max ( robHouses ( 0 , nums . length - 2 ) , robHouses ( 1 , nums . length - 1 ) ) ;
34+ } ;
35+
You can’t perform that action at this time.
0 commit comments