Skip to content

Commit 8643cc7

Browse files
committed
solve: house robber 2
1 parent 6571ded commit 8643cc7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

house-robber-ii/evan.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def rob(self, nums: List[int]) -> int:
6+
def linear_rob(nums: List[int]) -> int:
7+
house_length = len(nums)
8+
9+
if house_length == 0:
10+
return 0
11+
if house_length == 1:
12+
return nums[0]
13+
if house_length == 2:
14+
return max(nums[0], nums[1])
15+
16+
dp = [nums[0], max(nums[0], nums[1])]
17+
18+
for index in range(2, house_length):
19+
dp.append(max(dp[index - 1], dp[index - 2] + nums[index]))
20+
21+
return dp[-1]
22+
23+
house_length = len(nums)
24+
25+
if house_length < 3:
26+
return linear_rob(nums)
27+
28+
first_house_selected_result = linear_rob(nums[:-1])
29+
second_house_selected_result = linear_rob(nums[1:])
30+
31+
return max(first_house_selected_result, second_house_selected_result)

0 commit comments

Comments
 (0)