Skip to content

Commit 3d97426

Browse files
committed
add solution: house-robber-ii
1 parent ff631d5 commit 3d97426

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

house-robber-ii/dusunax.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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]))

0 commit comments

Comments
 (0)