Sub topic 14
Coin change: counting ways and minimum coins
This chapter assumes you know the 0/1 knapsack recurrence, the difference between memoization and tabulation, and Big-O notation. Coin change is an unbounded knapsack: each coin value may be used any number of times. It comes in two forms that look alike but need different loop structures. You will see both.
The two problems
Given coin denominations and a target amount A:
- Minimum coins: find the fewest coins that sum to
A, or report that it is impossible. - Counting ways: find how many distinct multisets of coins sum to
A. Order does not matter, so1+2and2+1are the same way.
Both have optimal substructure. After you remove one coin c from a solution for a, what remains is a solution for a - c. Both have overlapping subproblems, because many different coin sequences lead to the same remaining amount.
Minimum coins
Let dp[a] be the fewest coins needed to make a.
- Base case:
dp[0] = 0. - Recurrence:
dp[a] = 1 + min(dp[a - c])over all coinsc <= a. - Unreachable amounts: start every other cell at infinity. Infinity plus 1 is still infinity, so impossibility propagates.
- Fill order: increasing
a, becausedp[a]depends only on smaller amounts.
def min_coins(coins, amount):
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
print(min_coins([1, 3, 4], 6)) # 2
print(min_coins([2], 3)) # -1
print(min_coins([5], 0)) # 0For coins {1, 3, 4}, the table for amounts 0 to 6 is:
| Amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Fewest coins | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
The cell for 6 is 1 + min(dp[5], dp[3], dp[2]) = 1 + min(2, 1, 2) = 2, which corresponds to 3+3.
Several arrows land on dp[2]. That sharing is the overlap that makes the table worthwhile. The time is O(nA) for n coins, and the space is O(A).
Why greedy fails here
Greedy takes the largest coin that fits. For {1, 3, 4} and amount 6 it picks 4+1+1, which is 3 coins, while the optimum is 3+3. Greedy is correct only for special systems such as {1, 5, 10, 25}, where an exchange argument works. Without a proof, use dynamic programming.
Counting ways
Let dp[a] be the number of multisets of coins that sum to a.
- Base case:
dp[0] = 1, the empty selection. - Recurrence: process one coin at a time, and for each coin do
dp[a] += dp[a - c].
def count_ways(coins, amount):
dp = [1] + [0] * amount
for c in coins:
for a in range(c, amount + 1):
dp[a] += dp[a - c]
return dp[amount]
print(count_ways([1, 2, 5], 5)) # 4
print(count_ways([3], 2)) # 0
print(count_ways([7], 0)) # 1For {1, 2, 5} and amount 5, the row after each coin is:
| After coin | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 2 | 2 | 3 | 3 |
| 5 | 1 | 1 | 2 | 2 | 3 | 4 |
The four ways are 5, 2+2+1, 2+1+1+1 and 1+1+1+1+1.
Loop order decides what you count
The coin loop must be outside and the amount loop inside. Each coin type is then introduced once, so a fixed coin order produces each multiset once. The amount loop runs upward so a coin can be reused.
If you swap the loops, the code counts sequences, where 1+2 and 2+1 differ:
def count_sequences(coins, amount):
dp = [1] + [0] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a:
dp[a] += dp[a - c]
return dp[amount]
print(count_sequences([1, 2, 5], 5)) # 9Edge cases and complexity
- Amount 0 needs 0 coins and has exactly 1 way.
- Coins larger than the current amount must be skipped, or the index goes negative.
- Use an infinity sentinel for minimum coins. A sentinel like
-1insidemingives wrong answers. - Both algorithms take O(nA) time and O(A) space. This is pseudo-polynomial:
Ais a numeric value, not the input length, so doubling the number of bits inAsquares the work. - Counting answers grow fast. Fixed-width integer languages may overflow, and exam questions often ask for the result modulo a prime.
Exercise
How many ways can you make 6 from coins {2, 3}, with order ignored?
Show answer
Two ways: 2+2+2 and 3+3. The counting table after coin 2 is [1,0,1,0,1,0,1], and adding coin 3 gives dp[6] = 1 + dp[3] = 1 + 1 = 2.
Exercise
For coins {1, 5, 6, 9} and amount 11, does greedy give the minimum number of coins? What does dynamic programming give?
Show answer
No. Greedy takes 9+1+1, which is 3 coins. Dynamic programming finds 5+6, which is 2 coins, from dp[11] = 1 + min(dp[10], dp[6], dp[5], dp[2]) = 1 + min(2, 1, 1, 2) = 2.