Sub topic 9
One-dimensional problems: coin change
This chapter assumes you can write Python loops and functions, read Big-O notation, and already know what a DP state, a recurrence, and tabulation mean from earlier chapters. Here you apply them to a problem whose state is one integer, so the whole table fits in one list.
The problem
You are given coin denominations, such as [1, 3, 4], and a target amount, such as 6. You have an unlimited supply of each coin. You must find the fewest coins that sum exactly to the amount, or report that no combination works.
Many people first try a greedy approach: always take the largest coin that fits. For amount 6 that gives 4 + 1 + 1, which is three coins. The best answer is 3 + 3, which is two coins. A greedy choice can block a better combination later. DP avoids this because it tries every last coin and keeps the best result.
State, recurrence, and base case
The state is one number, a, the amount still to be made. Define dp[a] as the fewest coins that sum to a.
- Base case:
dp[0] = 0, because zero coins make amount zero. - Recurrence:
dp[a] = min(dp[a - c] + 1)over every coincwithc <= a. - Unreachable amounts: if no coin leads to a reachable smaller amount,
dp[a]stays at infinity.
The recurrence says that the last coin you use is some c. What remains, a - c, must itself be made optimally. That is optimal substructure in its plainest form.
Fill order
Every dependency dp[a - c] has a smaller index than a, because coins are positive. Filling the list from index 1 upward therefore guarantees that each entry's inputs are already final.
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([1, 5, 10], 0)) # 0Here is the filled table for coins [1, 3, 4]:
| a | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| dp[a] | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
Cost
The table has amount + 1 states, and each state does work proportional to the number of coins. Time is O(amount × len(coins)) and space is O(amount). You cannot reduce space the way you can for Fibonacci, because dp[a] may look back as far as the largest coin.
Common errors
- Initializing with 0 instead of infinity. If you do this, every
minreturns 0. Unreached amounts must start at a value larger than any real answer. - Returning infinity to the caller. Convert it to a sentinel such as
-1at the boundary, as the code above does. - Forgetting
c <= a. Without this check,dp[a - c]uses a negative index. In Python that silently reads from the end of the list instead of raising an error. - Confusing "fewest coins" with "number of ways." Counting combinations uses a different recurrence and a different loop order (see the exercise).
Exercise
Trace min_coins([2, 5], 3). What does each entry of dp hold after the loop, and what does the function return?
Show answer
dp[0] = 0. dp[1] stays inf because no coin is 1 or smaller. dp[2] = dp[0] + 1 = 1. dp[3] tries coin 2, which gives dp[1] + 1 = inf, and coin 5 does not fit, so it stays inf. The function returns -1.
Exercise
Write ways(coins, amount) that counts the distinct combinations (order ignored) that sum to amount. What is ways([1, 2, 5], 5)?
Show answer
Start with w = [1] + [0] * amount. Then run "for c in coins: for a in range(c, amount + 1): w[a] += w[a - c]" and return w[amount]. Putting coins in the outer loop counts each multiset once. Swapping the loops would count orderings instead. The result is 4: 5, 2+2+1, 2+1+1+1, and 1+1+1+1+1.