House robber and coin change
🌍 In real life. A charity collects donations along a street of five houses that have pledged 2, 7, 9, 3 and 1 hundred taka. Neighbours who are visited one after the other get annoyed, so the volunteers never knock on two houses side by side. Which houses give the most? (Puzzle books tell it as a robber who mustn't trip two neighbouring alarms; the sums are the same.)
The idea in one sentence: when each step is a choice, let the recurrence try every option for the last decision and keep the best; the table then holds the best answer for every smaller street.
Its words:
- choice: what you decide about the last item: rob house i or skip it; which coin to use last
- best of the options:
maxwhen collecting,minwhen paying - impossible state: an amount that no mix of coins can make, written ∞
The house robber, step by step:
- state:
dp[i]is the most from the first i houses - choice for house i: skip it (
dp[i − 1]), or rob it and so skip house i − 1 (dp[i − 2] + money) dp[i] = max(dp[i − 1], dp[i − 2] + houses[i − 1]), withdp[0] = 0anddp[1]= the first house- the answer is the last cell
Watch it: at house 4 the 3 isn't worth breaking up 2 + 9, so it is skipped:
Making change with the fewest coins. Lesson 56.1 showed greedy failing for coins 1, 3 and 4. DP tries every coin as the last one: if the last coin is c, the rest is the best way to make a − c, which the table already holds. So dp[a] = 1 + min(dp[a − c]) over the coins c that fit, with dp[0] = 0. For 6, the last coin 3 leaves 3, which one coin makes: 2 coins.
Why trying the last choice is enough. Every best answer has some last decision. If you try all of them and each one is followed by the best answer to what is left (which the table holds), the best of these is the best overall. This is optimal substructure: the rest of a best answer is itself a best answer to a smaller question.
What it costs, by counting. The robber fills n + 1 cells with 2 lookups each: O(n). Coin change fills amount + 1 cells and tries each of k coins at each: O(amount × k). For 1,000 taka and 9 kinds of note, 9,000 steps; Lesson 56.1's BFS does the same work in a different order.
def rob(houses):
dp = [0] * (len(houses) + 1) # dp[i]: the most from the first i houses
for i in range(1, len(houses) + 1):
skip = dp[i - 1] # leave house i alone
take = (dp[i - 2] if i >= 2 else 0) + houses[i - 1] # rob it, skip the one before
dp[i] = max(skip, take)
return dp[-1]
def coin_change(coins, amount):
INF = float("inf")
dp = [0] + [INF] * amount # dp[a]: fewest coins that make a
for a in range(1, amount + 1):
for c in coins:
if c <= a: # c could be the last coin
dp[a] = min(dp[a], dp[a - c] + 1)
return dp[amount] if dp[amount] != INF else -1
print(rob([2, 7, 9, 3, 1]))
print(coin_change([1, 3, 4], 6), coin_change([2], 3))Mistakes and edge cases.
- taking every other house: the best might skip two in a row: for 2, 1, 1, 2 the answer is 2 + 2 = 4, but neither alternating sum is more than 3
- no houses: the answer is 0, and the table is just
[0] - ∞ as a large number: using 9999 for "impossible" breaks when real answers grow;
float("inf")stays bigger than every count andinf + 1is stillinf - forgetting −1: an amount that can't be made must answer −1, not ∞
- amount 0: needs no coins at all: 0
Quiz
What does this print?
def rob(houses): dp = [0] * (len(houses) + 1) # dp[i]: the most from the first i houses for i in range(1, len(houses) + 1): skip = dp[i - 1] # leave house i alone take = (dp[i - 2] if i >= 2 else 0) + houses[i - 1] # rob it, skip the one before dp[i] = max(skip, take) return dp[-1] print(rob([2, 1, 1, 2]))In the robber's table, what does dp[i − 2] + houses[i − 1] mean?
- Rob house i, so the best before it must stop at house i − 2
- Skip house i
- Rob houses i and i − 1
What does this print?
def coin_change(coins, amount): INF = float("inf") dp = [0] + [INF] * amount # dp[a]: fewest coins that make a for a in range(1, amount + 1): for c in coins: if c <= a: # c could be the last coin dp[a] = min(dp[a], dp[a - c] + 1) return dp[amount] if dp[amount] != INF else -1 print(coin_change([1, 5, 6], 10))Why does coin change use float("inf") for amounts that can't be made?
- It is bigger than every real count, so min never picks it while a real way exists
- It makes the loop faster
- Python can't store −1 in a list
rob([5, 1, 1, 5]) gives 12 instead of 10. Which line is wrong?
def rob(houses): dp = [0] * (len(houses) + 1) for i in range(1, len(houses) + 1): skip = dp[i - 1] take = (dp[i - 1] if i >= 2 else 0) + houses[i - 1] dp[i] = max(skip, take) return dp[-1]
Coding tasks
Write
rob(houses):houseslists the money in each house along a street. Return the most you can collect without taking from two houses side by side.Write
coin_change(coins, amount): the fewest coins (each kind as often as you like) that make exactlyamount, or-1if it can't be made. Fill a tabledp[0..amount].