File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 213. House Robber II
3
+
4
+ house roober 1 + circular array
5
+
6
+ ## Solution
7
+ solve by using two cases:
8
+ - robbing from the first house to the last house
9
+ - robbing from the second house to the last house
10
+ '''
11
+ class Solution :
12
+ '''
13
+ A. pass indices to function
14
+ TC: O(n)
15
+ SC: O(1)
16
+ '''
17
+ def rob (self , nums : Lit [int ]) -> int :
18
+ if len (nums ) == 1 :
19
+ return nums [0 ]
20
+
21
+ def robbing (start , end ):
22
+ prev , maxAmount = 0 , 0
23
+
24
+ for i in range (start , end ):
25
+ prev , maxAmount = maxAmount , max (maxAmount , prev + nums [i ])
26
+
27
+ return maxAmount
28
+
29
+ return max (robbing (0 , len (nums ) - 1 ), robbing (1 , len (nums )))
30
+
31
+ '''
32
+ B. pass list to function
33
+ TC: O(n)
34
+ SC: O(n) (list slicing)
35
+ '''
36
+ def robWithSlicing (self , nums : List [int ]) -> int :
37
+ if len (nums ) == 1 :
38
+ return nums [0 ]
39
+
40
+ def robbing (nums ):
41
+ prev , maxAmount = 0 , 0
42
+
43
+ for num in nums :
44
+ prev , maxAmount = maxAmount , max (maxAmount , prev + num )
45
+
46
+ return maxAmount
47
+
48
+ return max (robbing (nums [1 :]), robbing (nums [:- 1 ]))
You can’t perform that action at this time.
0 commit comments