Dynamic programming: Coin Change
Dynamic programming (DP) is recursion that remembers. If a problem splits into smaller copies of itself, and the same small copies come up again and again, solve each one once and store the answer.
There are three steps from slow to fast:
- Recursion. "The fewest coins for 11 is one coin plus the fewest for 11 minus that coin." Correct, but exponential.
- Memo. Add
@functools.cacheso each amount is solved once. - Table. Fill a list
best[0..amount]from small to large, with no recursion and no depth limit.
The signal: "fewest", "most", or "how many ways", where choices overlap. Coin change is O(amount × coins) time.
A common mistake: greedy. Taking the biggest coin first fails for coins
[1, 3, 4] and amount 6: greedy gives 4+1+1, but 3+3 is better.
Exercise: finish min_coins so it returns the fewest coins that add up
to amount, or -1 if it can't be done. You have unlimited coins of each
value. Use a table. Press Check to run the tests.