Coin Change
Pattern: Subsequences and knapsack
Find the fewest coins that make the amount, using each coin as often as you like. best[a] = 1 + the minimum of best[a - c] over coins c; -1 if no coin fits.
The problem
Given coin values and an amount, return the fewest coins that add up to the amount, or -1 if it cannot be made.
Think first
- What was the last coin used?
- What is left after it?
- Why does greedy fail?
Hints
Brute force, and why it fails
Recursion over every last coin, without memory: exponential.
The key insight
Each amount's answer depends only on smaller amounts, so a table fills it in O(amount × coins).
Dry run
coins [1, 2, 5], amount 11. best[0] = 0, best[5] = 1, best[10] = 2.
Step 1 of 2
The plan
best = [0, inf, ...]
for a in 1..amount: for c: if c <= a: best[a] = min(best[a], best[a - c] + 1)
return -1 if best[amount] is inf
Complexity
- Time
O(amount × coins)- Space
O(amount)
One table.
Edge cases
- Amount 0: 0.
- Impossible: -1.
- One coin that does not divide the amount.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int coinChange(int[] coins, int amount) {
int[] best = new int[amount + 1]; // best[a]: the fewest coins making a
Arrays.fill(best, Integer.MAX_VALUE);
best[0] = 0;
for (int a = 1; a <= amount; a++)
for (int c : coins) // the last coin used was c
if (c <= a && best[a - c] != Integer.MAX_VALUE) best[a] = Math.min(best[a], best[a - c] + 1);
return best[amount] == Integer.MAX_VALUE ? -1 : best[amount];
}
}C++
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> best(amount + 1, INT_MAX); // best[a]: the fewest coins making a
best[0] = 0;
for (int a = 1; a <= amount; a++)
for (int c : coins) // the last coin used was c
if (c <= a && best[a - c] != INT_MAX) best[a] = min(best[a], best[a - c] + 1);
return best[amount] == INT_MAX ? -1 : best[amount];
}
};Python
class Solution:
def coinChange(self, coins: list[int], amount: int) -> int:
INF = float("inf")
best = [0] + [INF] * amount # best[a]: the fewest coins making a
for a in range(1, amount + 1):
for c in coins: # the last coin used was c
if c <= a and best[a - c] + 1 < best[a]:
best[a] = best[a - c] + 1
return -1 if best[amount] == INF else best[amount]Common mistakes
- Greedy.
- Returning infinity instead of -1.