Problem overview
The method coinChange(coins: number[], amount: number): number receives the available coin values and a target sum. Each value can be used as many times as needed. It returns the fewest coins that add up to exactly amount, or -1 if no combination does. When amount is 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 sum up to amount
The tempting shortcut is to take the largest coin that fits, again and again. It fails on coins = [1, 3, 4] and amount = 6: the greedy way gives 4 + 1 + 1, three coins, while 3 + 3 needs only two.
The reliable method is to answer the question for every sum from 0 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 total is dp[i - coin] + 1. Trying every coin as the last one and keeping the smallest result gives dp[i]. Each entry reuses answers for smaller sums, which is the dynamic programming.
A sum that can't be made needs a marker. Every coin is worth at least 1, so no sum i ever needs more than i coins. A count of amount + 1 can never be a real answer, so the table starts with that value everywhere, as a stand-in for "not reachable yet".
Step by step
- Create
dpas anumber[]withamount + 1entries, all set toamount + 1. - Set
dp[0] = 0. The sum 0 takes no coins, and every other sum is built on top of it. - Loop over the sums with
ifrom 1 up to and includingamount. By the timeiis reached, all smaller sums are final. - Loop over the coins with
for...of. Each coin is tried as the last one added to makei. - Skip coins that don't fit. The check
coin <= iavoids a negative indexi - coin. - Update with
Math.min:dp[i]becomes the smaller of its current value anddp[i - coin] + 1. Ifi - coincan't be made,dp[i - coin] + 1is more thanamount, so it never looks like a real answer. - Return
-1ifdp[amount]is still greater thanamount: no combination reached it. - Otherwise return
dp[amount].
The table for coins = [1, 3, 4] and amount = 6, as it looks after each value of i:
start [7,7,7,7,7,7,7]
dp[0] [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]
For i = 6 the coin 1 gives dp[5] + 1 = 3, the coin 3 gives dp[3] + 1 = 2, and the coin 4 gives dp[2] + 1 = 3. The smallest is 2, so the function returns 2.
The solution in TypeScript
class Solution {
coinChange(coins: number[], amount: number): number {
const dp: number[] = 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];
}
}
The TypeScript details worth knowing:
new Array(amount + 1).fill(amount + 1).new Array(k)with one number creates an array ofkempty slots, andfillwrites the same value into all of them.new Array(3).fill(3)gives[3, 3, 3]. The declared typenumber[]is only for the compiler: it is erased when the code becomes JavaScript.for...ofover an array gives the values themselves, not the indices, which is whatcoinneeds.for...inwould give the indices as strings.- Numbers are doubles. The sums here stay small, but a coin value can be as large as
2147483647. Forcoins = [2147483647]andamount = 10000, the checkcoin <= iis false every time, so the table is never updated and the function returns-1. No integer overflow can happen, because nothing is added to such a coin. - The second
ifhas no braces.if (dp[amount] > amount) return -1;is a single statement on one line, which is valid and common for guard clauses.
Complexity
Time: O(n · amount), where n is the number of coins. The outer loop runs amount times and the inner loop runs n times, with constant work inside. With at most 12 coins and an amount up to 10,000, that is at most about 120,000 steps.
Space: O(amount), for the table of amount + 1 numbers.
Edge cases and common mistakes
amount = 0. The table has one entry,dp[0] = 0, and the loops don't run. The function returns 0, which is the right answer: no coins at all.- No combination.
[2]with amount 3 returns-1. So does[5]with amount 3, where the only coin is bigger than the target. - Using greedy. It returns 3 for
[1, 3, 4]and 6, not 2. - Starting the table with 0 instead of
amount + 1.Math.minwould then never find anything smaller, and unreachable sums would look like they take no coins. - Starting the table with
Infinity. This also works in JavaScript, sinceInfinity + 1isInfinity, but the answer check would then have to compare withInfinity. The lesson usesamount + 1, which keeps every entry a normal number. - Dropping the
coin <= icheck. The indexi - coinwould be negative. In JavaScript,dp[-1]isundefined, andundefined + 1isNaN.Math.minthen returnsNaNand corrupts the table. - Looping up to
i < amount. The last sum,amountitself, would never be computed.
Testing
coins = [1, 2, 5],amount = 11gives3.coins = [2],amount = 3gives-1.coins = [1, 3, 4],amount = 6gives2.coins = [1],amount = 0gives0.coins = [5],amount = 3gives-1.coins = [2, 5],amount = 7gives2.coins = [186, 419, 83, 408],amount = 6249gives20.
