Sub topic 9
One-dimensional problems: coin change
This chapter applies the state, recurrence, and tabulation ideas from earlier chapters to a classic problem whose table is a single list. It assumes you are comfortable with Python loops and lists, recursion with base cases, Big-O notation, and the earlier chapters on defining a DP state, filling a table bottom-up, and counting states times work per state.
Coin change comes in two common forms. The optimization form asks for the fewest coins that add up to an amount. The counting form asks how many ways there are to make that amount. Both use a one-dimensional table indexed by amount. They differ in one detail that catches many people: the order of the loops.
The problem
You are given a list of coin denominations and a target amount. You may use each denomination as many times as you like. Return the smallest number of coins whose values sum exactly to the amount, or -1 if no combination works.
For example, with coins [1, 3, 4] and amount 6, the answer is 2 (3 + 3).
Why greedy fails
A natural first attempt is greedy: always take the largest coin that fits. For coins [1, 3, 4] and amount 6, greedy takes 4, then 1, then 1, which is three coins. The optimal answer is two coins (3 + 3).
Greedy happens to work for some coin systems, such as US coins [1, 5, 10, 25], but not in general. Taking the largest coin first can block a better split later. Dynamic programming avoids this by considering every possible last coin instead of committing early.
Defining the state and recurrence
Ask what the last coin in an optimal solution could be. If the last coin is c, the coins before it must make a - c, and they must do so with as few coins as possible. Otherwise you could swap in a better solution for a - c and improve the total. This is optimal substructure.
That gives the state and recurrence:
- State:
dp[a]is the fewest coins summing exactly toa. - Recurrence:
dp[a] = 1 + min(dp[a - c])over every coincwithc <= a. - Base case:
dp[0] = 0, since zero coins make amount zero. - Unreachable amounts:
dp[a] = infinitywhen no combination works.
Each dp[a] depends only on entries for smaller amounts. So filling the table from a = 1 up to a = amount guarantees every dependency is ready when you need it.
The diagram shows why plain recursion is wasteful here. dp[2] is reached from three different parents. With a table, it is computed once.
The bottom-up implementation
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, 25], 63)) # 6
print(min_coins([7], 0)) # 0A few details are worth noting:
dphasamount + 1entries so that indexamountexists.- Using
float('inf')for unreachable entries makes the comparison safe.INF + 1is stillINF, which is never less thandp[a], so an unreachable sub-amount never produces a candidate. - The final check turns infinity back into the
-1the problem asks for.
Tracing the table
Here is the filled table for coins [1, 3, 4] and amount 6. The "best last coin" column records which coin produced the minimum.
| a | Candidates `dp[a - c] + 1` | dp[a] | Best last coin |
|---|---|---|---|
| 0 | base case | 0 | none |
| 1 | c=1: dp[0]+1 = 1 | 1 | 1 |
| 2 | c=1: dp[1]+1 = 2 | 2 | 1 |
| 3 | c=1: 3, c=3: dp[0]+1 = 1 | 1 | 3 |
| 4 | c=1: 2, c=3: 2, c=4: 1 | 1 | 4 |
| 5 | c=1: 2, c=3: 3, c=4: 2 | 2 | 1 |
| 6 | c=1: 3, c=3: 2, c=4: 3 | 2 | 3 |
The last column already hints at how to recover the coins themselves: from 6, take a 3 and move to 3; from 3, take a 3 and reach 0. A later chapter covers this trace-back technique in full.
The same recurrence top-down
The recurrence translates directly into a memoized function:
from functools import lru_cache
def min_coins_memo(coins, amount):
INF = float('inf')
@lru_cache(maxsize=None)
def solve(a):
if a == 0:
return 0
best = INF
for c in coins:
if c <= a:
best = min(best, solve(a - c) + 1)
return best
result = solve(amount)
return result if result != INF else -1
print(min_coins_memo([1, 3, 4], 6)) # 2Only a is passed to the cached function, so coins (a list, which is not hashable) never has to be part of the cache key.
Complexity
Apply the rule from the complexity chapter: number of states times work per state.
| Quantity | Value |
|---|---|
| States | `amount + 1` |
| Work per state | `len(coins)` comparisons |
| Time | O(amount × len(coins)) |
| Space | O(amount) |
This running time is called pseudo-polynomial. It is polynomial in the numeric value of amount, not in the number of digits needed to write it. An amount of 10^9 makes a table of a billion entries even though the input is only ten digits long. When amounts are that large, this approach is impractical, and you need a different method or a bound on the problem.
The table cannot be shrunk the way Fibonacci's can. dp[a] may depend on dp[a - c] for the largest coin, so you must keep at least the last max(coins) entries. In practice the full list is simple and rarely the bottleneck.
Common errors
- Using 0 for "unreachable". If unreachable entries hold 0, they look like the best possible answer and corrupt every amount built on them. Use infinity, or
amount + 1, which is larger than any valid answer since the fewest coins can never exceedamountwhen the smallest coin is at least 1. - Initializing
dp[0]to infinity. Then nothing is reachable and every answer is-1. - Off-by-one table size.
[INF] * amountwithout the leading[0]gives onlyamountentries, anddp[amount]raises IndexError. - Coins of value 0 or less. A zero coin makes the memoized version call
solve(a)from insidesolve(a)forever, since the call is still in progress and not yet cached. A negative coin breaks the fill order becausea - cexceedsa. Validate denominations as positive integers at the boundary. - Assuming duplicates matter.
[1, 1, 3]gives the same answers as[1, 3]. Duplicates only waste a little time.
The counting variant and loop order
Now change the question: how many different ways can you make amount? Let ways[a] be the number of ways to make a, with ways[0] = 1 (one way to make zero: use no coins). Instead of taking a minimum, you add.
The catch is what "different ways" means. Are 1 + 2 and 2 + 1 the same way or two ways? The loop order decides.
def count_combinations(coins, amount):
# Order of coins does not matter: {1, 2} is counted once.
ways = [1] + [0] * amount
for c in coins:
for a in range(c, amount + 1):
ways[a] += ways[a - c]
return ways[amount]
def count_sequences(coins, amount):
# Order matters: 1+2 and 2+1 are counted separately.
ways = [1] + [0] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a:
ways[a] += ways[a - c]
return ways[amount]
print(count_combinations([1, 2], 3)) # 2: 1+1+1, 1+2
print(count_sequences([1, 2], 3)) # 3: 1+1+1, 1+2, 2+1With coins in the outer loop, the table first counts all ways using only the first coin, then extends them with the second coin, and so on. Each combination is built in one fixed coin order, so it is counted once. With amounts in the outer loop, every ways[a] considers every coin as the last one, so different orderings are counted as different sequences.
Counts grow fast. Python integers do not overflow, but in languages with fixed-size integers, or when a problem asks for the answer modulo a prime, apply the modulus on every addition.
Summary of the pattern
Coin change shows the general shape of one-dimensional DP:
- Index the state by a single quantity (here, the amount).
- Write the recurrence by asking what the last choice was.
- Set base cases and a sentinel for impossible states.
- Fill in an order where every dependency comes first.
- For counting problems, check that the loop order counts what the problem means.
The next chapter adds a second index, which is needed when the state depends on positions in two inputs at once.
Exercise
Fill in the min_coins table by hand for coins [2, 5] and amount 7. What does the function return, and which amounts from 0 to 7 are unreachable?
Show answer
dp = [0, inf, 1, inf, 2, 1, 3, 2]. dp[7] = dp[5] + 1 = 2 (2 + 5), so the function returns 2. Amounts 1 and 3 are unreachable: 1 is smaller than every coin, and 3 cannot be written as a sum of 2s and 5s.
Exercise
Give coin denominations and an amount where the greedy "largest coin first" strategy uses more coins than min_coins, and state both counts.
Show answer
One example is coins [1, 3, 4] with amount 6. Greedy takes 4 + 1 + 1 for 3 coins, while min_coins finds 3 + 3 for 2 coins. Another is coins [1, 5, 6, 9] with amount 11: greedy takes 9 + 1 + 1 (3 coins), while the optimum is 5 + 6 (2 coins).
Exercise
For coins [1, 2, 3] and amount 4, what do countcombinations and countsequences return? Explain the difference.
Show answer
countcombinations returns 4: {1,1,1,1}, {1,1,2}, {2,2}, {1,3}. countsequences returns 7: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2, 1+3, 3+1. The coin-outer loop builds each multiset in one fixed order, so it is counted once. The amount-outer loop lets any coin be last at every step, so each ordering counts separately.
Exercise
Why does mincoinsmemo([1], 5000) raise RecursionError while mincoins([1], 5000) does not, and what is the time complexity of mincoins for coins of length k and amount n?
Show answer
The memoized version calls solve(5000), then solve(4999), and so on down to solve(0). That chain is about 5000 frames deep, above Python's default limit of 1000. The tabulated version uses a loop, so the call stack never grows. Its time is O(n × k), with O(n) space.