Problem overview
The method coinChange receives a list coins of coin values and an integer amount. It returns the fewest coins that add up to exactly amount, or -1 if no combination does. Each value can be used any number of times. For an amount of 0 the answer is 0.
With coins = [1, 2, 5] and amount = 11 the answer is 3, from 5 + 5 + 1. With coins = [2] and amount = 3 the answer is -1, since 2s only make even sums.
Approach: the fewest coins for every smaller sum
The tempting shortcut is greedy: always take the largest coin that fits. It fails here: for coins = [1, 3, 4] and amount = 6 greedy takes 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination is far too slow, as the number of combinations grows very fast with the amount.
Dynamic programming solves the problem for every sum from 0 up to amount. Let dp[i] be the fewest coins that make the sum i. If the last coin added is coin, the coins before it make i - coin, so the candidate is dp[i - coin] + 1. Trying every coin and keeping the smallest candidate gives dp[i]. Each entry reuses entries for smaller sums, which are already filled.
Step by step
- Create
dpas[amount + 1] * (amount + 1): one entry per sum from 0 toamount. Every coin is worth at least 1, so no sumineeds more thanicoins. A count ofamount + 1can never be real, so it marks a sum that can't be made (yet). - Set
dp[0] = 0. The sum 0 takes no coins, and every other entry is built on top of it. - Loop
ioverrange(1, amount + 1), from the smallest sum up, so the smaller sums are done wheniis reached. - Loop over
coinswithcoin: each coin is tried as the last one added. - Check
coin <= i. A coin worth more thanidoesn't fit, andi - coinwould be a negative index. - Update
dp[i]tomin(dp[i], dp[i - coin] + 1). Ifi - coincan't be made,dp[i - coin] + 1is more thanamounttoo, so it never passes for a real answer. - If
dp[amount] > amount, return-1. Only a sum no combination makes keeps its starting value. - Otherwise return
dp[amount]. Foramount = 0the loops don't run and this returnsdp[0], which is 0.
The solution in Python
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for coin in coins:
if coin <= i:
dp[i] = min(dp[i], dp[i - coin] + 1)
if dp[amount] > amount:
return -1
return dp[amount]
For coins = [1, 3, 4] and amount = 6 the finished table is:
[0, 1, 2, 1, 1, 2, 2]
Reading it, dp[6] = 2 comes from dp[3] + 1. For coins = [2] and amount = 3 the table is:
[0, 4, 1, 4]
The entries 4 are the "can't be made" marker, which is amount + 1. The last one is greater than 3, so the function returns -1.
Python details worth knowing:
[amount + 1] * (amount + 1)repeats one integer, which is safe because integers are immutable. Repeating a list of lists this way is a different matter, because the rows would be the same object.- Python integers have no overflow, so using
amount + 1as "infinity" is safe.float('inf')would also work but turns the table into floats. minreturns the smaller of its two arguments.
Complexity
Time: O(n * amount), where n is the number of coin values: the two nested loops do constant work per pair. Space: O(amount) for the table.
Edge cases and common mistakes
- Amount 0.
coinChange([1], 0)returns 0, with no coins used. - Unreachable amounts.
coinChange([3, 7], 5)returns-1. - A coin equal to the amount.
coinChange([5], 5)returns 1. - Coins larger than the amount. Without the
coin <= icheck,dp[i - coin]uses a negative index, which Python reads from the end of the list instead of raising an error. The result is silently wrong. - Starting entries at 0. Then
minwould always keep 0 and every sum would look free. - Greedy. Taking the largest coin first gives 3 for
[1, 3, 4]and 6, but the answer is 2.
Testing
coins = [1, 2, 5],amount = 11gives3.coins = [2],amount = 3gives-1.coins = [1, 3, 4],amount = 6gives2.coins = [1],amount = 0gives0.coins = [2, 5],amount = 7gives2.coins = [3, 7],amount = 5gives-1.
