|
| 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