Algo-Sim › Dynamic Programming
Coin Change
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Fewest coins to make an amount: dp[a] is one more than the best dp[a − coin] over every coin that fits.
Problem
Given coin denominations coins (each available in unlimited supply) and an amount, return the fewest coins that add up to exactly amount, or -1 if it cannot be made.
Constraints
- 1 ≤ coins.length ≤ 12
- 1 ≤ coins[i] ≤ 2³¹ − 1
- 0 ≤ amount ≤ 10⁴
- Greedy (largest coin first) fails for some coin sets
Edge cases to test
- amount = 0:
0coins - Impossible amount:
-1 - Coins larger than the amount
Follow-up questions
- Why does greedy fail?
- With coins [1, 3, 4] and amount 6, greedy takes 4 + 1 + 1 but 3 + 3 is better. Greedy works only for canonical systems like real currencies.
- Is there a BFS view?
- Each amount is a node and each coin an edge; the fewest coins is the shortest path from 0: O(amount · coins).
Solution
Java
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int a = 1; a <= amount; a++) {
for (int coin : coins) {
if (coin <= a) {
dp[a] = Math.min(dp[a], dp[a - coin] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}Python
def coin_change(coins, amount):
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for a in range(1, amount + 1):
for coin in coins:
if coin <= a:
dp[a] = min(dp[a], dp[a - coin] + 1)
return -1 if dp[amount] > amount else dp[amount]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int coinChange(vector<int> &coins, int amount) {
vector<int> dp = vector<int>(amount + 1);
fill(dp.begin(), dp.end(), amount + 1);
dp[0] = 0;
for (int a = 1; a <= amount; a++) {
for (int coin : coins) {
if (coin <= a) {
dp[a] = std::min(dp[a], dp[a - coin] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)