House Robber Problem
Description
LeetCode Problem 198.
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 400
Solution
Approach: Dynamic Programming with Two Variables
Trying every set of non-adjacent houses takes exponential time. Instead, look at the houses from left to right and decide for each one whether to rob it.
Let best(i) be the most money we can get from houses 0 to i. For house i there are two choices:
- Skip it: we keep
best(i - 1). - Rob it: we cannot have robbed house
i - 1, so we getbest(i - 2) + nums[i].
So best(i) = max(best(i - 1), best(i - 2) + nums[i]). Each step only looks two values back, so two variables are enough: best (the answer for the houses so far) and bestBeforePrev (the answer without the last house). Both start at 0, which handles one-house and two-house streets without special cases.
A common mistake is to assume the best plan takes every other house (all even or all odd positions). In [2, 1, 1, 2] the best is to rob the first and last houses for 4, which skips two houses in a row; the recurrence finds this because skipping is always allowed.
Complexity: O(n) time and O(1) space, where n is the length of nums.
class Solution:
def rob(self, nums: List[int]) -> int:
best_before_prev = 0 # best total using the houses before the previous one
best = 0 # best total using all houses seen so far
for money in nums:
# Either skip this house, or rob it on top of the best that ends two houses back.
new_best = max(best, best_before_prev + money)
best_before_prev = best
best = new_best
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.