Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a list of coin values coins and a target amount. You have an unlimited supply of every coin. Return the fewest coins whose values add up to exactly amount. If no combination works, return -1. If amount is 0, the answer is 0 (no coins).
There are 1 to 12 coin types, each value is between 1 and 2³¹ − 1, and amount is at most 10⁴. Below, k is the number of coin types.
Example: coins = [1, 2, 5], amount = 11 → 3, because 5 + 5 + 1 = 11.
Start with brute force
Greedy first, because everyone tries it. "Take the biggest coin that fits, repeat." With coins = [1, 3, 4] and amount = 6, greedy takes 4 + 1 + 1 (3 coins), but 3 + 3 uses only 2. Greedy is wrong.
Real brute force: try every coin as the next one, recursively, and keep the smallest count.
def fewest(a):
if a == 0: return 0
return 1 + min(fewest(a - c) for c in coins if c <= a) # (ignoring "impossible")Each call branches k ways and the depth can reach amount, so it's exponential. With amount = 10⁴ it never finishes.
Building the intuition
Run the recursion in your head for coins = [1, 3, 4], amount = 6. fewest(6) asks fewest(5), fewest(3) and fewest(2). Then fewest(5) asks fewest(4), fewest(2), fewest(1). fewest(2) is already being asked twice. There are only 7 different questions here (fewest(0) to fewest(6)), asked many times each.
So store the answer for every amount from 0 up to amount. Walk through the recipe:
- State.
dp[a]means the fewest coins that add up to exactlya, or "impossible". - Recurrence. Think about the last coin in the pile. If it's coin
c, the rest of the pile makesa − c, and it had better be the smallest such pile. You don't know which coin is last, so try them all:dp[a] = 1 + min(dp[a − c])over every coinc ≤ a. - Base case.
dp[0] = 0. Zero coins make zero. - Order.
dp[a]reads smaller amounts, so fillafrom 1 upwards.
This shape is called the unbounded knapsack: you can reuse each item (coin) as many times as you like, which is why dp[a − c] may itself already contain coin c.
The optimal approach
- Let
INF = amount + 1. No real answer can need that many coins (even using only 1s you'd need justamount). - Make
dpof sizeamount + 1, allINF. Setdp[0] = 0. - For
afrom 1 toamount, for each coinc:- if
c ≤ aanddp[a − c] + 1 < dp[a], setdp[a] = dp[a − c] + 1.
- if
- Return
dp[amount]if it isn'tINF, else-1.
The subtle detail: the "impossible" value. If you use INT_MAX for impossible, then dp[a − c] + 1 overflows to a negative number and wins every min. amount + 1 is safe: it's bigger than any real answer, and adding 1 still fits. An impossible dp[a − c] gives amount + 2, which can never beat anything.
Space. The table is already one-dimensional and every cell may be read later, so there's no further space optimisation here.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
INF = amount + 1 # more coins than any real answer can need (amount 1s at most)
# dp[a] = the fewest coins that add up to exactly a (INF if a can't be made)
dp = [INF] * (amount + 1)
dp[0] = 0 # zero coins make zero
for a in range(1, amount + 1):
for c in coins:
# use c as the last coin: the rest, a - c, must be made as cheaply as possible
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return dp[amount] if dp[amount] != INF else -1class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int INF = amount + 1; // more coins than any real answer can need (amount 1s at most)
// dp[a] = the fewest coins that add up to exactly a (INF if a can't be made)
vector<int> dp(amount + 1, INF);
dp[0] = 0; // zero coins make zero
for (int a = 1; a <= amount; a++) {
for (int c : coins) {
// use c as the last coin: the rest, a - c, must be made as cheaply as possible
if (c <= a && dp[a - c] + 1 < dp[a]) {
dp[a] = dp[a - c] + 1;
}
}
}
return dp[amount] != INF ? dp[amount] : -1;
}
};class Solution {
public int coinChange(int[] coins, int amount) {
int INF = amount + 1; // more coins than any real answer can need (amount 1s at most)
// dp[a] = the fewest coins that add up to exactly a (INF if a can't be made)
int[] dp = new int[amount + 1];
Arrays.fill(dp, INF);
dp[0] = 0; // zero coins make zero
for (int a = 1; a <= amount; a++) {
for (int c : coins) {
// use c as the last coin: the rest, a - c, must be made as cheaply as possible
if (c <= a && dp[a - c] + 1 < dp[a]) {
dp[a] = dp[a - c] + 1;
}
}
}
return dp[amount] != INF ? dp[amount] : -1;
}
}/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function (coins, amount) {
const INF = amount + 1; // more coins than any real answer can need (amount 1s at most)
// dp[a] = the fewest coins that add up to exactly a (INF if a can't be made)
const dp = new Array(amount + 1).fill(INF);
dp[0] = 0; // zero coins make zero
for (let a = 1; a <= amount; a++) {
for (const c of coins) {
// use c as the last coin: the rest, a - c, must be made as cheaply as possible
if (c <= a && dp[a - c] + 1 < dp[a]) {
dp[a] = dp[a - c] + 1;
}
}
}
return dp[amount] !== INF ? dp[amount] : -1;
};Dry run
coins = [1, 3, 4], amount = 6, so INF = 7. Each row tries every coin as the last one.
| a | last coin 1: dp[a − 1] + 1 | last coin 3: dp[a − 3] + 1 | last coin 4: dp[a − 4] + 1 | dp[a] |
|---|---|---|---|---|
| 0 | — | — | — | 0 (base) |
| 1 | dp[0] + 1 = 1 | too big | too big | 1 |
| 2 | dp[1] + 1 = 2 | too big | too big | 2 |
| 3 | dp[2] + 1 = 3 | dp[0] + 1 = 1 | too big | 1 |
| 4 | dp[3] + 1 = 2 | dp[1] + 1 = 2 | dp[0] + 1 = 1 | 1 |
| 5 | dp[4] + 1 = 2 | dp[2] + 1 = 3 | dp[1] + 1 = 2 | 2 |
| 6 | dp[5] + 1 = 3 | dp[3] + 1 = 2 | dp[2] + 1 = 3 | 2 |
Final table: dp = [0, 1, 2, 1, 1, 2, 2]. The answer is 2: last coin 3, on top of dp[3] = 1 (one more 3). Greedy's 4 + 1 + 1 shows up in the row for a = 6 as the "last coin 4" option, worth 3, and loses.
Complexity
- Time: O(amount · k).
amountcells, and each tries allkcoins. At most 10⁴ × 12 = 120,000 steps. - Space: O(amount) for the table.
Edge cases and traps
amount = 0. Return 0, not -1. The loop doesn't run anddp[0] = 0.- Impossible amounts.
coins = [2],amount = 3→ -1. Make sureINFis converted back to -1. - Huge coin values. A coin can be 2³¹ − 1. Check
c ≤ abefore computinga − c; never computea + c. - Overflow from
INT_MAX + 1. Useamount + 1as the sentinel, as above. - Greedy. Correct for some coin systems (like Indian rupee notes), wrong in general. Always test
[1, 3, 4], 6.
Say it in the interview
"Greedy fails, for example on coins 1, 3, 4 and amount 6. Let
dp[a]be the fewest coins that make exactlya. The last coin is somec, and the rest must be optimal fora − c, sodp[a] = 1 + min(dp[a − c])over all coins that fit.dp[0] = 0, and I useamount + 1for impossible so nothing overflows. Fillingafrom 1 up costs O(amount times the number of coins) time and O(amount) space."
Follow-ups interviewers ask
- "Count the number of ways to make the amount instead?" That's Coin Change II. Loop over coins on the outside and amounts inside, with
dp[a] += dp[a − c]anddp[0] = 1, so each combination is counted once regardless of order. - "Why not BFS?" You can: each amount is a node, each coin an edge, and the shortest path from 0 to
amountis the answer. Same complexity; the DP is shorter to write. - "What if each coin can be used only once?" That's the 0/1 knapsack. Loop
adownwards for each coin so a coin isn't reused within its own pass.
Practise the same idea
This is Day 83 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free