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+ # Time Complexity: O(n) -> iterate through the houses twice, each in O(n) time.
2+ # Space Complexity: O(1) -> use a few extra variables, no additional data structures.
3+
4+ class Solution :
5+ def rob (self , nums : List [int ]) -> int :
6+ if not nums :
7+ return 0
8+ if len (nums ) == 1 :
9+ return nums [0 ]
10+
11+ # track the max money from two houses before and last house.
12+ var1 , var2 = 0 , 0
13+
14+ # robbing from first house to second-last house (excluding last house)
15+ for i in nums [:- 1 ]:
16+ # store previous max before updating.
17+ temp = var1
18+ # either rob this house or skip it.
19+ var1 = max (var2 + i , var1 )
20+ # move to the next house.
21+ var2 = temp
22+
23+ # same logic, but robbing from second house to last house.
24+ vaar1 , vaar2 = 0 , 0
25+
26+ for i in nums [1 :]:
27+ temp = vaar1
28+ vaar1 = max (vaar2 + i , vaar1 )
29+ vaar2 = temp
30+
31+ # take the max of both cases.
32+ return max (var1 , vaar1 )
You can’t perform that action at this time.
0 commit comments