Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 52f09df

Browse files
committedOct 24, 2024·
Implemented House Robber, DP
1 parent 6e24935 commit 52f09df

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
 

‎dynamic_programming/house_robber.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
2+
3+
def house_robber(houses: list[int]) -> int:
4+
"""
5+
Solves the House Robber problem using memoization (caching).
6+
Returns the maximum amount of money that can be robbed without triggering alarms.
7+
Problem URL: https://leetcode.com/problems/house-robber/
8+
9+
Args:
10+
houses: A list of integers representing the amount of money in each house.
11+
Returns:
12+
int: The maximum amount of money that can be robbed without triggering alarms.
13+
Raises:
14+
ValueError: If there are no houses in the input list.
15+
16+
Examples:
17+
>>> house_robber([2, 3, 2])
18+
4
19+
>>> house_robber([1, 2, 3, 1])
20+
4
21+
>>> house_robber([0, 0, 0, 0])
22+
0
23+
>>> house_robber([10, 15, 20, 25])
24+
40
25+
>>> house_robber([50])
26+
50
27+
>>> house_robber([5, 15, 5, 15, 5])
28+
30
29+
"""
30+
number_of_houses = len(houses)
31+
if number_of_houses == 0:
32+
raise ValueError("There must be at least one house")
33+
34+
memo = [-1 for _ in range(number_of_houses)]
35+
36+
def dp(n: int) -> int:
37+
if n >= number_of_houses:
38+
return 0
39+
# If the house has been visited before, avoid revisiting (Memoization)
40+
if memo[n] != -1:
41+
return memo[n]
42+
43+
# Decide to rob this house and skip the next, or skip this one
44+
rob = houses[n] + dp(n + 2)
45+
dont_rob = dp(n + 1)
46+
47+
memo[n] = max(rob, dont_rob)
48+
return memo[n]
49+
50+
return dp(0)
51+
52+

0 commit comments

Comments
 (0)
Please sign in to comment.