Coin change (fewest coins)
Medium TimeExponential naive (shown); O(amount × coins) memoised SpaceO(amount) stack
Coins come in the denominations coins, each in unlimited supply. Return the fewest coins that make amount exactly. The amount is a whole number, zero or more, and an amount of 0 needs no coins at all. An amount that no combination can make comes back as Infinity.
Examples
Example 1
- Input
- coins = [1, 3, 4]amount = 6
- Output
23 + 3= 6 in two coins; taking the largest first gives4 + 1 + 1, which is three.
Example 2
- Input
- coins = [3]amount = 5
- Output
- Threes make 3, 6, 9 and so on, so 5 is unreachable and no count comes back.
Infinity
The Code
function coinChange(coins, amount) {
if (amount === 0) return 0;
if (amount < 0) return Infinity;
let best = Infinity;
for (const coin of coins) {
best = Math.min(best, coinChange(coins, amount - coin) + 1);
}
return best;
}
coinChange([1, 3, 4], 6);Done
The first 34 calls, of 106. This one does not fit on a page.
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.
- House robber Rob a house and skip its neighbour, or skip to the next.