Coin Change
Difficulty: Medium
Given coin values coins (unlimited supply of each) and a target amount, return the fewest coins that add up to exactly that amount. If it can't be done, return -1.
Examples
Input: coins = [1, 2, 5], amount = 11
Output: 3
11 = 5 + 5 + 1, using 3 coins.
Input: coins = [2], amount = 3
Output: -1
You can only ever make even amounts with 2-value coins.
Input: coins = [1], amount = 0
Output: 0
Zero coins are needed to make an amount of 0.
Constraints
1 <= coins.length <= 12
1 <= coins[i] <= 2^31 - 1
0 <= amount <= 10^4
Approach
Consider the last coin c in an optimal solution for amount a. The rest is an optimal solution for a - c. You don't know which coin came last, so try them all and keep the fewest total.
That gives fewest(a) = 1 + min(fewest(a - c)) over every coin c that fits in a, with fewest(0) = 0 as the base case. Computing it bottom-up, from 0 to the target, means smaller amounts are solved before you need them, avoiding the repeated work of plain recursion.
Solutions
Brute Force — Plain Recursion
Try every coin as the last one, recurse on the remainder, and keep the option with the fewest coins. Correct, but recomputes the same amounts many times.
function coinChange(coins, amount) {
function fewest(remaining) {
if (remaining === 0) return 0;
if (remaining < 0) return Infinity;
let best = Infinity;
for (const coin of coins) {
const result = fewest(remaining - coin);
if (result + 1 < best) best = result + 1;
}
return best;
}
const answer = fewest(amount);
return answer === Infinity ? -1 : answer;
}Time: O(coins.length ^ amount) · Space: O(amount) — recursion depth
Optimal — Bottom-Up Tabulation
Compute the fewest coins for every amount from 0 to the target, reusing smaller amounts already solved.
function coinChange(coins, amount) {
// dp[a] = fewest coins to make amount a; amount+1 stands in for "impossible"
const dp = new Array(amount + 1).fill(amount + 1);
dp[0] = 0;
for (let a = 1; a <= amount; a++) {
for (const coin of coins) {
if (coin <= a) {
dp[a] = Math.min(dp[a], dp[a - coin] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}Time: O(amount * coins.length) · Space: O(amount)