Problem overview
The method coinChange receives an array 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 coin value can be used any number of times, and an amount of 0 needs 0 coins.
With coins = [1, 2, 5] and amount = 11 the answer is 3 (5 + 5 + 1). With coins = [2] and amount = 3 it is -1, because 2s only make even sums. With coins = [1, 3, 4] and amount = 6 it is 2 (3 + 3).
Approach: the fewest coins for every smaller sum
The third example shows why a greedy strategy is unsafe. Always taking the largest coin that fits gives 4 + 1 + 1 for 6, which is three coins, while 3 + 3 uses two. Instead, compute the answer for every sum from 0 up to amount.
Let dp[i] be the fewest coins that make the sum i. Consider the last coin added. If it is coin, the coins before it make i - coin, so the best result through that coin is dp[i - coin] + 1. Trying every coin and keeping the smallest gives dp[i]. Each entry reuses answers for smaller sums that were already computed, which is what makes this dynamic programming. Checking all combinations of coins would take exponential time.
Why does the last coin work as the way to split the problem? Any combination that makes i has some coin in it. Remove one copy of that coin and what remains is a combination for i - coin. If the whole combination is the fewest possible for i, the remainder must also be the fewest for i - coin, since a smaller one would improve the whole. So the best answer for i always comes from the best answer for some smaller sum, and trying every coin covers every possibility.
The table needs a marker for "can't be made". Every coin is worth at least 1, so no sum i ever needs more than i coins, and a count of amount + 1 can never be a real answer. The table starts filled with that value, and any entry that still holds it at the end is unreachable.
Step by step
- Create
dpwithamount + 1entries, all equal toamount + 1.new Array(amount + 1).fill(amount + 1)does it. The array has one slot per sum from 0 toamount. - Set
dp[0]to 0. The sum 0 takes no coins, and every other entry is built on top of it. - Loop
ifrom 1 toamount, inclusive. Eachdp[i]needs only smaller sums, which are finished by then. - Loop over
coinswithfor...of. 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. - Take the minimum:
dp[i] = Math.min(dp[i], dp[i - coin] + 1). Ifi - coincan't be made,dp[i - coin] + 1is larger thanamount, so it never passes for a real answer. - After the loops, return
-1ifdp[amount] > amount. 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 JavaScript
class Solution {
coinChange(coins, amount) {
const dp = new Array(amount + 1).fill(amount + 1);
dp[0] = 0;
for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (coin <= i) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
if (dp[amount] > amount) return -1;
return dp[amount];
}
}
A few JavaScript details help here:
new Array(k)createskempty slots, andfillsets every one of them to the same value. Filling with a number is safe, because numbers are copied by value.for (const coin of coins)walks the values of the array. Usefor...offor values and notfor...in, which walks the indices as strings.dpis aconst, but only the variable can't be reassigned: the entries of the array can still change, which is what the loop does.- Reading outside an array doesn't throw.
dp[-2]givesundefined, andundefined + 1isNaN, whichMath.minturns intoNaN. That is why thecoin <= icheck matters.
Tracing coins = [1, 3, 4], amount = 6
The table before the loop is [0,7,7,7,7,7,7]. After each round of the outer loop it looks like this:
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]
At i = 6 the coin 3 gives dp[3] + 1 = 2, which beats the coin 1 (dp[5] + 1 = 3) and the coin 4 (dp[2] + 1 = 3). The answer is 2.
Complexity
With n coins, the outer loop runs amount times and the inner loop n times, so the time is O(n · amount). The table has amount + 1 entries, so the space is O(amount).
Edge cases and common mistakes
- Amount 0. The answer is 0, and
coinChange([5], 0)returns 0 because the table is just[0]. - Unreachable sums.
coinChange([2], 1)returns-1, and so doescoinChange([2], 3). In the second case the table ends as[0,4,1,4]: the entries for 1 and 3 keep the marker value 4. - Greedy choice. For
[1, 3, 4]and amount 6, taking the largest coin first gives 3 coins, but the answer is 2. - Skipping the
coin <= icheck. The code then reads a negative index, getsundefined, andNaNcan end up in the table. - Returning
dp[amount]directly. For an unreachable amount that returns the marker value (4 in the example above) instead of-1.
Testing
Results from the reference solution:
coins [1, 2, 5], amount 11 -> 3
coins [2], amount 3 -> -1
coins [1, 3, 4], amount 6 -> 2
coins [1, 3, 4], amount 7 -> 2
coins [5], amount 0 -> 0
coins [2], amount 1 -> -1
