Coin Change
Medium · Dynamic programming
Jump to codeGiven positive coin denominations and a nonnegative amount, find the fewest coins needed to make that amount with unlimited copies. Return −1 when it is impossible.
Examples
Example 1
coins = [1,2,5] amount = 11
Output: 3
Example 2
coins = [2] amount = 3
Output: -1
Constraints
- 1 <= coins.length <= 10
- 1 <= coins[i] <= 2^31 - 1
- 0 <= amount <= 10000
Need a hint?
The best solution for a total can extend a smaller reachable total by one coin.
Asked in real interviews
Candidates reported versions of Coin Change from these company interviews. Some company questions are locked and open with Premium or XP.
- Find the Minimum Number of Coins for an AmountPinterest
- Compute drawdown, profit, and coin changeSquarepoint
Solution approach
Initialize dp[0] = 0 and other entries to an unreachable sentinel. For each total from 1 to amount, consider each coin no larger than the total and minimize dp[total−coin] + 1. Return −1 if the target is still unreachable.
Complexity
O(amount × number of denominations) time and O(amount) space.
Python reference solution
def coinChange(coins, amount):
dp = [0] + [amount + 1] * amount
for total in range(1, amount + 1):
for coin in coins:
if coin <= total:
dp[total] = min(dp[total], dp[total - coin] + 1)
return dp[amount] if dp[amount] <= amount else -1
JavaScript solution
function coinChange(coins, amount) {
const dp = Array(amount + 1).fill(amount + 1);
dp[0] = 0;
for (let total = 1; total <= amount; total++) {
for (const coin of coins) if (coin <= total) dp[total] = Math.min(dp[total], dp[total - coin] + 1);
}
return dp[amount] <= amount ? dp[amount] : -1;
}
Java solution
import java.util.*;
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int total = 1; total <= amount; total++) {
for (int coin : coins) if (coin <= total) dp[total] = Math.min(dp[total], dp[total - coin] + 1);
}
return dp[amount] <= amount ? dp[amount] : -1;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int coinChange(vector<int> &coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int total = 1; total <= amount; total++) {
for (int coin : coins) if (coin <= total) dp[total] = min(dp[total], dp[total - coin] + 1);
}
return dp[amount] <= amount ? dp[amount] : -1;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
2,
5
],
11
]3
[
[
2
],
3
]-1
[
[
1
],
0
]0
[
[
2,
5,
10
],
6
]3
[
[
1,
3,
4
],
6
]2
Drafts are saved per language in this browser when storage is available.