Problem overview
The function coinChange receives a slice coins of coin values and an integer amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination works. Each coin value can be used as many times as you like. When amount is 0 the answer is 0.
For coins = [1, 2, 5] and amount = 11, the answer is 3: 5 + 5 + 1. Two coins can't do it, since the largest sum of two coins is 10. For coins = [2] and amount = 3 the answer is -1, because 2s only make even sums.
Approach: the fewest coins for every sum up to amount
Taking the largest coin that fits looks natural, but it isn't always right. With coins = [1, 3, 4] and amount = 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two.
Trying every combination works but is far too slow. Dynamic programming gives a better route. 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 cost is dp[i - coin] + 1. Trying every coin as the last one and keeping the smallest result gives dp[i]. Filling the table from small sums to large ensures that dp[i - coin] is ready when it is needed.
Sums that can't be made need a marker. Every coin is worth at least 1, so no sum i needs more than i coins, and a count of amount + 1 can never be a real answer. It works as "impossible, so far". It also behaves well in the formula: if i - coin can't be made, dp[i - coin] + 1 is larger than amount too, so it never passes for a real result.
For coins = [1, 3, 4] and amount = 6, the table after each sum is:
start [0 7 7 7 7 7 7]
i = 1 [0 1 7 7 7 7 7]
i = 2 [0 1 2 7 7 7 7]
i = 3 [0 1 2 1 7 7 7]
i = 4 [0 1 2 1 1 7 7]
i = 5 [0 1 2 1 1 2 7]
i = 6 [0 1 2 1 1 2 2]
The last entry is 2, the answer. The 7 at the start is amount + 1.
Step by step
- Create
dpwithmake([]int, amount+1): one slot for each sum from 0 toamount, filled with zeros. - Loop over
dpwithrange, keeping only the indexi. - Set every
dp[i]toamount + 1, the "can't make it yet" marker. - Set
dp[0]to 0. The sum 0 takes no coins, and every other sum is built on top of it. - Loop over the sums
ifrom 1 toamount, inclusive. Each one needs only smaller sums, which are already done. - Loop over
coinswithfor _, coin := range coins. The_discards the index. Each coin is tried as the last one added to makei. - Check
coin <= i. A larger coin doesn't fit in the sum, andi - coinwould be a negative index. - Update
dp[i]to the smaller of its current value anddp[i-coin]+1. - If
dp[amount]is still aboveamount, return-1: only a sum that 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 Go
func coinChange(coins []int, amount int) int {
dp := make([]int, amount+1)
for i := range dp {
dp[i] = amount + 1
}
dp[0] = 0
for i := 1; i <= amount; i++ {
for _, coin := range coins {
if coin <= i {
dp[i] = min(dp[i], dp[i-coin]+1)
}
}
}
if dp[amount] > amount {
return -1
}
return dp[amount]
}
The Go details worth a closer look:
makezero-fills.make([]int, 3)is[0 0 0]. That is why the code writesamount + 1into every slot afterwards.for i := range dpgives indexes only. With two names,for i, v := range dp, you would get the value as well.for _, coin := range coinsdoes the opposite: it throws away the index and keeps the value.- The built-in
min. Since Go 1.21,minandmaxare built in, with no import. The lessons use Go 1.22. - Braces are required. Even a one-statement
ifneeds{ }, and the opening brace has to be on the same line as the condition. - Large coin values are safe. Coins can be as large as 2147483647 (2^31 - 1), which fits in Go's 64-bit
int. Such a coin never passes thecoin <= icheck, sinceiis at most 10000.
Complexity
Time: O(n · amount), where n is the number of coins. The outer loop runs amount times and the inner loop tries all n coins each time.
Space: O(amount). The table has amount + 1 entries.
Edge cases and common mistakes
- Amount 0. The answer is 0 coins.
dphas one entry,dp[0] = 0, and it is returned. - Skipping the
coin <= icheck. Thendp[i-coin]uses a negative index. In Go that stops the program with a run-time panic (index out of range [-1]). - Starting the table at 0. If every slot started at 0,
minwould never replace it, and every sum would look like it takes no coins. - Starting with a huge value such as
math.MaxInt. Thendp[i-coin]+1overflows and wraps around to a very negative number, whichminpicks. The markeramount + 1avoids this. - Greedy choice. Always taking the largest coin fails on
[1, 3, 4]with 6. - Using
i < amount. The loop would leavedp[amount]at its marker, and the function would return-1for every amount above 0.
Testing
coins = [1, 2, 5],amount = 11gives3.coins = [2],amount = 3gives-1.coins = [1, 3, 4],amount = 6gives2.coins = [1],amount = 0gives0.coins = [5, 10],amount = 3gives-1.coins = [2147483647],amount = 10000gives-1.coins = [186, 419, 83, 408],amount = 6249gives20.
