32. Dynamic Programming 1D (Coin Change)
Solve each subproblem once, store the answer, and build bigger answers from smaller ones. Coin change finds the fewest coins for an amount, where greedy choices fail.
How it works
Define dp[a] = fewest coins that sum to a. The base case is dp[0] = 0. For any other amount, the last coin used was some coin c, leaving a - c, so dp[a] = min(dp[a - c] + 1) over all coins c <= a. Filling the table from 0 upward guarantees every dp[a - c] is ready when needed.
With coins 1, 3, 4 and amount 6, greedy (always take the biggest coin) picks 4 + 1 + 1 = 3 coins. DP finds 3 + 3 = 2 coins.
Diagram
flowchart LR
d0["dp 0 = 0"]
d1["dp 1 = 1"]
d2["dp 2 = 2"]
d3["dp 3 = 1"]
d4["dp 4 = 1"]
d5["dp 5 = 2"]
d6["dp 6 = 2"]
d0 -->|"+1"| d1
d1 -->|"+1"| d2
d2 -->|"+1"| d3
d0 -->|"+3"| d3
d3 -->|"+1"| d4
d1 -->|"+3"| d4
d0 -->|"+4"| d4
d4 -->|"+1"| d5
d2 -->|"+3"| d5
d1 -->|"+4"| d5
d5 -->|"+1"| d6
d3 -->|"+3"| d6
d2 -->|"+4"| d6
Step-by-step trace
Input: Coins [1, 3, 4], amount 6.
| amount a | Candidates dp[a - c] + 1 | dp[a] | Last coin used |
|---|---|---|---|
| 0 | base case | 0 | - |
| 1 | c=1: dp[0]+1=1 | 1 | 1 |
| 2 | c=1: dp[1]+1=2 | 2 | 1 |
| 3 | c=1: dp[2]+1=3; c=3: dp[0]+1=1 | 1 | 3 |
| 4 | c=1: dp[3]+1=2; c=3: dp[1]+1=2; c=4: dp[0]+1=1 | 1 | 4 |
| 5 | c=1: dp[4]+1=2; c=3: dp[2]+1=3; c=4: dp[1]+1=2 | 2 | 1 |
| 6 | c=1: dp[5]+1=3; c=3: dp[3]+1=2; c=4: dp[2]+1=3 | 2 | 3 |
Result: Answer: 2 coins (3 + 3).
Complexity
| Operation | Time | Space |
|---|---|---|
| Coin change, n coins, amount A | O(n * A) | O(A) |
Python reference implementation
def coin_change(coins, amount):
"""Fewest coins that sum to amount, or -1 if impossible."""
INF = float("inf")
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return dp[amount] if dp[amount] != INF else -1
Common mistakes and tips
- Initialize unreachable amounts to infinity, not 0, and return -1 if
dp[A]stays infinite. - Counting the number of ways is a different recurrence: loop over coins on the outside to avoid counting orders twice.
- Recipe for any DP: define the state in words, write the recurrence, set base cases, pick a fill order.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Backtracking (Subsets) | Next: Dynamic Programming 2D (Longest Common Subsequence) |