Skip to content

Commit 1b16576

Browse files
committed
House Robber Dynamic Programming
1 parent 274d14a commit 1b16576

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

House_Robber.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# You are a professional robber planning to rob houses along a street. Each house
2+
# has a certain amount of money stashed, the only constraint stopping you from robbing
3+
# each of them is that adjacent houses have security system connected and it will
4+
# automatically contact the police if two adjacent houses were broken into on the same night.
5+
#
6+
# Given a list of non-negative integers representing the amount of money of each
7+
# house, determine the maximum amount of money you can rob tonight without alerting the police.
8+
#
9+
# Example 1:
10+
#
11+
# Input: [1,2,3,1]
12+
# Output: 4
13+
# Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
14+
# Total amount you can rob = 1 + 3 = 4.
15+
# Example 2:
16+
#
17+
# Input: [2,7,9,3,1]
18+
# Output: 12
19+
# Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
20+
# Total amount you can rob = 2 + 9 + 1 = 12.
21+
22+
23+
class Solution:
24+
def rob(self, nums):
25+
prevMax = 0
26+
currMax = 0
27+
28+
for num in nums:
29+
prevMax, currMax = currMax, max(prevMax + num, currMax)
30+
31+
return currMax

0 commit comments

Comments
 (0)