Coin Change
You are given an integer array coins representing coin denominations and an integer amount. Return the fewest number of coins needed to make up that amount. If that amount cannot be made up by any combination of the coins, return -1. The fewest coins for amount i is 1 plus the fewest coins already found for amount i minus a coin's value , tried for every coin and keeping the smallest result — a classic bottom-up table built from amount 0 up to the target.
Constraints
- 1 ≤ coins.length ≤ 12
- 1 ≤ coinsi ≤ 231 - 1
- 0 ≤ amount ≤ 104
Example
coins = [1, 2, 5], amount = 113Explanation 11 = 5 + 5 + 1, using 3 coins — no combination uses fewer.
In plain terms
- Denomination
- One of the fixed coin values you are allowed to use, like 1, 2, or 5.
Fill the fewest-coins table from amount 0 up to the target
One cell per amount from 0 to 5. Only dp[0] = 0 is known — zero coins are needed to make amount 0.
What happens in this step
coins = [1, 2, 5] dp[0] = 0 The base case: making amount 0 requires no coins at all. Amounts 1 to 5 are still blank.
Steps to visualize
- Set dp0 = 0 — it takes zero coins to make amount zero.
- For every amount from 1 upward, try every coin no larger than the amount.
- dpamount = 1 + the smallest dp[amount - coin] found across all usable coins.
- The value at dpamount is the answer, or -1 if it was never reached.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
One cell per amount from 0 to 5. Only dp[0] = 0 is known — zero coins are needed to make amount 0.
What happens in this step
coins = [1, 2, 5] dp[0] = 0 The base case: making amount 0 requires no coins at all. Amounts 1 to 5 are still blank.
Solution
function coinChange(coins, amount) {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (coin <= i && dp[i - coin] + 1 < dp[i]) {
dp[i] = dp[i - coin] + 1;
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}- Time
- O(amount * coins.length)
- Space
- O(amount)
Test cases
| Input | Expected | Covers |
|---|---|---|
coins = [1, 2, 5], amount = 11 | 3 | example from the docstring |
coins = [2], amount = 3 | -1 | amount cannot be made with the given coins |
coins = [1], amount = 0 | 0 | smallest valid amount, no coins needed |
coins = [3], amount = 9 | 3 | a single coin denomination that divides evenly |
coins = [5], amount = 3 | -1 | every coin is larger than the target amount |
coins = [7], amount = 7 | 1 | amount exactly equals one coin |
coins = [1, 2, 5], amount = 100 | 20 | a larger amount solved entirely with the biggest coin |