15% off all plans & roadmaps Use code
See plansCoin Change
- LeetCode 322
- Medium
- Dynamic Programming (DP) Patterns
- 1D Array (Coin Change / Unbounded Knapsack Style)
Updated
TL;DR: Find the fewest coins that sum to a target amount, or -1 if impossible. Build answers for every amount from 0 up to the target, since each amount needs only the answers for smaller amounts.
Problem
You are given an integer array coins holding coin denominations and an integer amount holding a target sum of money.
Return the fewest coins needed to make exactly that amount. If no combination of the coins can make the amount, return -1. You have an unlimited supply of each coin.
Example 1
Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1
Example 2
Input: coins = [2], amount = 3 Output: -1
Example 3
Input: coins = [1], amount = 0 Output: 0
Constraints
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4
Constraints that matter
amountis at most 10^4, so a table with one cell per amount is tiny. An O(amount * coins) solution does at most 120,000 steps.coins.lengthis at most 12, so the inner loop over coins is a small constant factor. Plain recursion still blows up because its branching compounds with depth.coins[i]can reach 2^31 - 1. Any coin larger than the current amount is useless, and computingi - coinfor such a coin must not index the array out of range.amountcan be 0, and the answer is then 0 coins. The base case has to cover this without special handling.- Coin values are arbitrary, so no divisibility structure exists. This rules out greedy and forces you to compare every coin at every amount.
Hints
Hint 1
This is a minimum-cost question over a sum, and the sum is small.
Hint 2
Define solve(rem) as the fewest coins for the remaining amount rem.
Solution
Intuition
This is a minimum-cost question over a sum, and the sum is small. That points to Dynamic Programming on a 1D array. The state is a single number, the remaining amount, so there are at most 10^4 + 1 distinct subproblems.
Picture a row of numbered mailboxes, one for each amount from 0 to the target. Each box holds the fewest coins needed to reach that amount, and you fill them left to right so every box you need is already written when you get to it.
Look at the last coin in an optimal answer for amount a. Whatever coin c it is, the coins before it form an optimal answer for a - c. If they were not optimal, you could swap in a better set and improve the answer for a. So the best answer for a is 1 plus the best answer among a - c over all coins c.
A direct recursion on that rule recomputes the same amounts many times. Amount 2 is reached from 7 by a 5-coin, from 6 by a 4-coin, from 5 by a 3-coin, and so on. Caching each amount's answer turns the exponential tree into at most amount distinct calls. Filling the cache from small amounts to large removes the recursion entirely.
Greedy does not work here. With coins 1, 3, 4 and amount 6, taking the biggest coin gives 4 + 1 + 1, which is three coins. The best is 3 + 3, which is two. Only trying every coin at every amount is safe.
Worked example
Input: coins = [1, 3, 4, 5], amount = 7 Output: 2 Explanation: The best split is 3 + 4, which uses two coins. Using 5 leaves 2, which needs two more 1-coins, so that path costs 3. Using the largest coin first does not win here, which is why a greedy pick is unsafe.
Approach 1: Brute force recursion
Define solve(rem) as the fewest coins for the remaining amount rem. Try every coin as the next one, recurse on rem - coin, and keep the smallest result plus one. Return -1 from a branch that cannot finish.
This tries every ordered sequence of coins whose sum does not overshoot. It is correct because it enumerates every possible answer. It is slow for the reason covered next.
Steps
- If
remis 0, return 0. Ifremis negative, return -1 because the coin overshot. - Set
bestto -1, meaning no solution found yet. - For each coin, call
solve(rem - coin). - If that result is not -1 and
result + 1beatsbest, updatebest. - Return
bestafter trying all coins. - Call
solve(amount)and return its value.
Dry run
Take coins [1, 3, 4, 5] and amount 7. solve(7) branches into solve(6), solve(4), solve(3) and solve(2).
solve(4)finds the 4-coin and returns 1, so the 3-coin branch gives 2.solve(3)finds the 3-coin and returns 1, so the 4-coin branch gives 2.solve(6)returns 2 (for example 1 + 5), so the 1-coin branch gives 3.solve(2)returns 2 (1 + 1), so the 5-coin branch gives 3.
The minimum is 2, which matches the expected output. Note that solve(1) and solve(2) run again inside the other branches. Each repeat redoes its whole subtree.
Complexity
| Time | O(n^amount) worst case |
|---|---|
| Space | O(amount) |
Here n is the number of coins and amount is the target. The recursion goes at most amount levels deep, because the smallest coin is at least 1, and every call branches n ways. That gives at most n^amount calls. The only memory is the call stack, which holds at most amount frames.
PythonTested in our runner
from typing import List, Optional
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
def solve(rem: int) -> int:
if rem == 0:
return 0
if rem < 0:
return -1
best = -1
for c in coins:
r = solve(rem - c)
if r >= 0 and (best < 0 or r + 1 < best):
best = r + 1
return best
return solve(amount)JavaTested in our runner
import java.util.*;
class Solution {
public int coinChange(int[] coins, int amount) {
return solve(coins, amount);
}
private int solve(int[] coins, int rem) {
if (rem == 0) return 0;
if (rem < 0) return -1;
int best = -1;
for (int c : coins) {
int r = solve(coins, rem - c);
if (r >= 0 && (best < 0 || r + 1 < best)) {
best = r + 1;
}
}
return best;
}
};C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
return solve(coins, amount);
}
private:
int solve(vector<int>& coins, int rem) {
if (rem == 0) return 0;
if (rem < 0) return -1;
int best = -1;
for (int c : coins) {
int r = solve(coins, rem - c);
if (r >= 0 && (best < 0 || r + 1 < best)) {
best = r + 1;
}
}
return best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function(coins, amount) {
const solve = (rem) => {
if (rem === 0) return 0;
if (rem < 0) return -1;
let best = -1;
for (const c of coins) {
const r = solve(rem - c);
if (r >= 0 && (best < 0 || r + 1 < best)) {
best = r + 1;
}
}
return best;
};
return solve(amount);
};GoTested in our runner
func coinChange(coins []int, amount int) int {
var solve func(rem int) int
solve = func(rem int) int {
if rem == 0 {
return 0
}
if rem < 0 {
return -1
}
best := -1
for _, c := range coins {
r := solve(rem - c)
if r >= 0 && (best < 0 || r+1 < best) {
best = r + 1
}
}
return best
}
return solve(amount)
}C#Tested in our runner
public class Solution {
public int coinChange(int[] coins, int amount) {
return Solve(coins, amount);
}
private int Solve(int[] coins, int rem) {
if (rem == 0) return 0;
if (rem < 0) return -1;
int best = -1;
foreach (int c in coins) {
int r = Solve(coins, rem - c);
if (r >= 0 && (best < 0 || r + 1 < best)) {
best = r + 1;
}
}
return best;
}
}Approach 2: Top-down memoization
What's slow: the recursion answers the same question, such as the best for amount 2, again and again from different branches. Each repeat expands a full subtree. The answer for a given rem never changes, so the repeated work is pure waste.
The insight that fixes it: store each answer the first time you compute it. Keep a memo array indexed by remaining amount. A cached value, including -1 for impossible, is returned immediately. Only amount distinct values of rem exist, so each is expanded once.
Steps
- Create
memoof sizeamount + 1, filled with a marker (-2) meaning not computed yet. - In
solve(rem), return 0 forrem == 0and -1 forrem < 0. - If
memo[rem]is not the marker, return it. - Loop over the coins, recurse on
rem - coin, and track the smallestresult + 1among valid results. - Store
bestinmemo[rem], using -1 when nothing worked. - Return
solve(amount).
Dry run
Use coins [1, 3, 4, 5] and amount 7. The first descent goes through the 1-coin each time, so the call chain is 7, 6, 5, 4, 3, 2, 1, 0. On the way back up, the memo fills with memo[1]=1, memo[2]=2, memo[3]=1, memo[4]=1, memo[5]=1, memo[6]=2.
No amount below 7 is recomputed after that. When solve(7) tries the 3-coin it reads memo[4]=1 at once. The 4-coin reads memo[3]=1, and the 5-coin reads memo[2]=2. The candidates for 7 are 3, 2, 2 and 3, so memo[7]=2, which is the expected output.
Complexity
| Time | O(amount * n) |
|---|---|
| Space | O(amount) |
Here n is the number of coins. There are amount + 1 distinct values of rem, and each is computed once and does n units of work in its loop. Cached lookups cost O(1). The memo holds amount + 1 integers, and the recursion stack is at most amount deep, so space is O(amount).
PythonTested in our runner
import sys
from typing import List, Optional
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# Depth can reach amount when a 1-coin exists.
sys.setrecursionlimit(max(sys.getrecursionlimit(), 30000))
memo = [-2] * (amount + 1) # -2 means not computed yet
def solve(rem: int) -> int:
if rem == 0:
return 0
if rem < 0:
return -1
if memo[rem] != -2:
return memo[rem]
best = -1
for c in coins:
r = solve(rem - c)
if r >= 0 and (best < 0 or r + 1 < best):
best = r + 1
memo[rem] = best
return best
return solve(amount)JavaTested in our runner
import java.util.*;
class Solution {
public int coinChange(int[] coins, int amount) {
int[] memo = new int[amount + 1];
Arrays.fill(memo, -2); // -2 means not computed yet
return solve(coins, amount, memo);
}
private int solve(int[] coins, int rem, int[] memo) {
if (rem == 0) return 0;
if (rem < 0) return -1;
if (memo[rem] != -2) return memo[rem];
int best = -1;
for (int c : coins) {
int r = solve(coins, rem - c, memo);
if (r >= 0 && (best < 0 || r + 1 < best)) {
best = r + 1;
}
}
memo[rem] = best;
return best;
}
};C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> memo(amount + 1, -2); // -2 means not computed yet
return solve(coins, amount, memo);
}
private:
int solve(vector<int>& coins, int rem, vector<int>& memo) {
if (rem == 0) return 0;
if (rem < 0) return -1;
if (memo[rem] != -2) return memo[rem];
int best = -1;
for (int c : coins) {
int r = solve(coins, rem - c, memo);
if (r >= 0 && (best < 0 || r + 1 < best)) {
best = r + 1;
}
}
memo[rem] = best;
return best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function(coins, amount) {
const memo = new Array(amount + 1).fill(-2); // -2 means not computed yet
memo[0] = 0;
// Top-down memoization with an explicit stack to avoid call stack overflow
const stack = [amount];
while (stack.length > 0) {
const rem = stack[stack.length - 1];
if (memo[rem] !== -2) {
stack.pop();
continue;
}
// Make sure all subproblems are computed first
let pending = false;
for (const c of coins) {
const next = rem - c;
if (next > 0 && memo[next] === -2) {
stack.push(next);
pending = true;
}
}
if (pending) continue;
let best = -1;
for (const c of coins) {
const next = rem - c;
if (next < 0) continue;
const r = memo[next];
if (r >= 0 && (best < 0 || r + 1 < best)) best = r + 1;
}
memo[rem] = best;
stack.pop();
}
return memo[amount];
};GoTested in our runner
func coinChange(coins []int, amount int) int {
memo := make([]int, amount+1)
for i := range memo {
memo[i] = -2 // -2 means not computed yet
}
var solve func(rem int) int
solve = func(rem int) int {
if rem == 0 {
return 0
}
if rem < 0 {
return -1
}
if memo[rem] != -2 {
return memo[rem]
}
best := -1
for _, c := range coins {
r := solve(rem - c)
if r >= 0 && (best < 0 || r+1 < best) {
best = r + 1
}
}
memo[rem] = best
return best
}
return solve(amount)
}C#Tested in our runner
public class Solution {
public int coinChange(int[] coins, int amount) {
int[] memo = new int[amount + 1];
Array.Fill(memo, -2); // -2 means not computed yet
return Solve(coins, amount, memo);
}
private int Solve(int[] coins, int rem, int[] memo) {
if (rem == 0) return 0;
if (rem < 0) return -1;
if (memo[rem] != -2) return memo[rem];
int best = -1;
foreach (int c in coins) {
int r = Solve(coins, rem - c, memo);
if (r >= 0 && (best < 0 || r + 1 < best)) {
best = r + 1;
}
}
memo[rem] = best;
return best;
}
}
Solution pattern
1D Array (Coin Change / Unbounded Knapsack Style)
Approach 3: Bottom-up DP tableOptimal1D Array (Coin Change / Unbounded Knapsack Style)
What's slow: memoization has the right operation count, but it pays for recursion. The call stack can grow to amount frames, and some runtimes overflow at 10^4 levels. Every call also carries function-call overhead.
The insight that fixes it: every dependency points to a smaller amount. So fill a table dp in increasing order, and each cell finds its inputs already done. dp[i] is the fewest coins for amount i. Start with dp[0] = 0 and everything else at amount + 1, a value no real answer can reach because amount 1-coins is the worst case. At the end, a cell still holding amount + 1 means impossible.
Why it is correct. Let dp[i] be the fewest coins for amount i, and assume every smaller amount is already correct. The last coin in any best answer for i must be some coin c, and the other coins must be a best answer for i - c. So dp[i] = 1 + min(dp[i - c]) over coins c that fit. Trying every coin means no candidate is skipped, so the minimum is never missed.
Steps
- Create
dpof sizeamount + 1, filled withamount + 1. - Set
dp[0] = 0. - For each amount
ifrom 1 toamount, loop over every coin. - Skip a coin when
coin > i, since it cannot be used. - Otherwise set
dp[i] = min(dp[i], dp[i - coin] + 1). - After the loops, return -1 if
dp[amount] > amount, else returndp[amount].
Dry run
Coins [1, 3, 4, 5], amount 7. The table starts as [0, 8, 8, 8, 8, 8, 8, 8], using 8 as the sentinel. Each row shows the candidates dp[i - coin] + 1 for the coins that fit.
| i | candidates from coins 1, 3, 4, 5 | dp[i] |
|---|---|---|
| 1 | 1: dp[0]+1 = 1 | 1 |
| 2 | 1: dp[1]+1 = 2 | 2 |
| 3 | 1: 3, 3: dp[0]+1 = 1 | 1 |
| 4 | 1: 2, 3: dp[1]+1 = 2, 4: dp[0]+1 = 1 | 1 |
| 5 | 1: 2, 3: dp[2]+1 = 3, 4: dp[1]+1 = 2, 5: dp[0]+1 = 1 | 1 |
| 6 | 1: 2, 3: dp[3]+1 = 2, 4: dp[2]+1 = 3, 5: dp[1]+1 = 2 | 2 |
| 7 | 1: 3, 3: dp[4]+1 = 2, 4: dp[3]+1 = 2, 5: dp[2]+1 = 3 | 2 |
The final table is [0, 1, 2, 1, 1, 1, 2, 2]. dp[7] = 2 is not greater than 7, so the function returns 2.
Complexity
| Time | O(amount * n) |
|---|---|
| Space | O(amount) |
Here n is the number of coins. The outer loop runs amount times and the inner loop runs n times, so the work is amount * n, at most 120,000 steps under the constraints. Each step is one comparison and one addition. The only extra memory is dp, which has amount + 1 cells.
PythonTested in our runner
from typing import List, Optional
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# amount + 1 is larger than any real answer, so it acts as infinity.
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for c in coins:
if c <= i:
dp[i] = min(dp[i], dp[i - c] + 1)
return -1 if dp[amount] > amount else dp[amount]JavaTested in our runner
import java.util.*;
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
// amount + 1 acts as infinity and cannot overflow when we add 1.
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int c : coins) {
if (c <= i) {
dp[i] = Math.min(dp[i], dp[i - c] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
// amount + 1 acts as infinity and cannot overflow when we add 1.
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int c : coins) {
if (c <= i) {
dp[i] = min(dp[i], dp[i - c] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};JavaScriptTested in our runner
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}
*/
var coinChange = function(coins, amount) {
// amount + 1 acts as infinity, larger than any real answer.
const dp = new Array(amount + 1).fill(amount + 1);
dp[0] = 0;
for (let i = 1; i <= amount; i++) {
for (const c of coins) {
if (c <= i) {
dp[i] = Math.min(dp[i], dp[i - c] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
};GoTested in our runner
func coinChange(coins []int, amount int) int {
// amount + 1 acts as infinity, larger than any real answer.
dp := make([]int, amount+1)
for i := range dp {
dp[i] = amount + 1
}
dp[0] = 0
for i := 1; i <= amount; i++ {
for _, c := range coins {
if c <= i && dp[i-c]+1 < dp[i] {
dp[i] = dp[i-c] + 1
}
}
}
if dp[amount] > amount {
return -1
}
return dp[amount]
}C#Tested in our runner
public class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
// amount + 1 acts as infinity and cannot overflow when we add 1.
Array.Fill(dp, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
foreach (int c in coins) {
if (c <= i) {
dp[i] = Math.Min(dp[i], dp[i - c] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}Common mistakes
- Taking the largest coin first, as in
while amount > 0: take max coin <= amount. This fails on coins [1, 3, 4] with amount 6, where it returns 3 instead of 2. Try every coin at every amount and keep the minimum. - Filling
dpwithInteger.MAX_VALUEorINT_MAXand then computingdp[i - coin] + 1. The addition overflows to a negative number and wins themin. Useamount + 1as the sentinel, or check for the sentinel before adding. - Forgetting the guard
if coin <= iand indexingdp[i - coin]directly. A negative index is a bug in Java and C++, and in Python it silently reads from the end of the list. Coins can be as large as 2^31 - 1, so this triggers often. - Returning
dp[amount]without the final check. An unreachable amount then returns the sentinel, such as 4 for amount 3 with coins [2]. Compare againstamount + 1and return -1. - Using recursion with no cache, or caching only successful answers. Without caching the work is exponential. If impossible results are not stored, the same dead branches are re-explored. Store -1 in the memo too.
- Setting
dp[0]wrong, for example to 1 or leaving it at the sentinel. Every answer is built ondp[0] = 0, so a wrong base shifts or breaks every cell. Amount 0 must return 0 coins.
Edge cases
coins = [1], amount = 0returns 0, because no coins are needed for a zero target.coins = [2], amount = 3returns -1, because odd totals cannot be made from 2-coins.coins = [5, 10], amount = 3returns -1, because every coin is larger than the amount. The guardcoin <= imust skip them all.coins = [1], amount = 10000returns 10000. This is the maximum depth case for recursion and the largest answer for the table.coins = [2147483647], amount = 5returns -1. A huge coin must not cause overflow or an out-of-range index.coins = [186, 419, 83, 408], amount = 6249returns 20. This case has no pattern a greedy rule can use, and DP handles it.- Duplicate-looking or unsorted coins, such as
[5, 1, 2], give the same answer as sorted input. The solution never depends on coin order.
Follow-ups interviewers ask
- How do you return the actual coins used, not only the count?
- Keep a second array
choicewherechoice[i]records the coin that gavedp[i]its best value. After filling the table, start atamountand repeat: addchoice[i]to the result and move toi - choice[i]until you reach 0. This costs O(amount) extra space and O(answer length) extra time. - Can breadth-first search solve it, and how does it compare?
- Yes. Treat each amount from 0 to
amountas a node, with an edge fromatoa + coin. The shortest path from 0 toamountis the answer, and BFS finds it level by level, with the level number equal to the coin count. A visited array keeps it at O(amount * n) time and O(amount) space, the same as DP. DP is shorter to write, while BFS can exit early when it reaches the target. - How does the solution change if you must count the number of ways to make the amount?
- That is Coin Change II. Replace
minwith a sum, sodp[i] += dp[i - coin]. Put the coin loop on the outside and the amount loop on the inside, so each combination is counted once. With the amount loop outside, you count ordered sequences, so 1+2 and 2+1 count separately.
Coin Change FAQ
What is the time complexity of Coin Change?
The memoized and bottom-up solutions run in O(amount * n), where n is the number of coin denominations. There are amount + 1 subproblems and each tries n coins. The plain recursion without a cache is exponential, bounded by n^amount.
Why use dynamic programming for Coin Change?
The best answer for an amount is 1 plus the best answer for some smaller amount, and the same smaller amounts appear in many branches. That is optimal substructure with overlapping subproblems. A table stores each amount's answer once, so the exponential tree becomes amount * n steps.
Why does the greedy approach fail for Coin Change?
Picking the biggest coin first only works for some coin systems. With coins [1, 3, 4] and amount 6, greedy takes 4 + 1 + 1 for three coins, while 3 + 3 uses two. Because coin values are arbitrary here, you have to compare all choices at every amount.
Can Coin Change be solved in O(1) extra space?
No, not in general. The recurrence for amount i needs the answers for i - coin for each coin, so you must remember past results. You can shrink the table to a rolling window as wide as the largest coin that is at most amount, but in the worst case that is still O(amount).
Why is the sentinel amount + 1 and not infinity?
The most coins any valid answer can use is amount, with all 1-coins, so amount + 1 can never be a real answer. It also fits in an int and adding 1 to it cannot overflow. In Python you can use float('inf'), but an integer sentinel keeps the types uniform.
What is the difference between Coin Change and Coin Change II?
Coin Change (LeetCode 322) asks for the fewest coins and uses min. Coin Change II asks for the number of combinations and uses addition with the coin loop outside the amount loop. Both fill a 1D array indexed by amount.
Asked at
See which companies ask this — Pro
Related problems
- Coin Change II · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Combination Sum IV · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Perfect Squares · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Distinct Subsequences · next harder, same pattern
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns
- Edit Distance · same pattern: Dynamic Programming (DP) Patterns
- House Robber · same pattern: Dynamic Programming (DP) Patterns
- Longest Common Subsequence · same pattern: Dynamic Programming (DP) Patterns