Problem 51 · Dynamic Programming
Coin Change
01Problem
Given coin denominations and an amount, return the fewest coins needed to make the amount, or -1 if impossible (unlimited coins of each kind).
02Key insight
Unbounded knapsack: dp[a] = 1 + min(dp[a - c]). Greedy fails for non-canonical coin systems like [1,3,4] with amount 6.
03Solution
Try it first.
TimeO(amount * len(coins))
SpaceO(amount)
tests.py · 4 passing
tests.pypython4 lines
assert coin_change([1,2,5], 11) == 3
assert coin_change([2], 3) == -1
assert coin_change([1], 0) == 0
assert coin_change([1,3,4], 6) == 204Staff-level follow-up
Amount is 10^12? The DP table is infeasible; use BFS/Dijkstra on residues mod the largest coin, or exploit structure if the coin system is canonical.