Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Dynamic Programming

The Fewest Coins.

Watch the explainer

Don't memorize coin change — watch the table fill. To make an amount with the fewest coins, first solve every smaller amount, then each new amount is just “one coin plus the best way to make the rest”. Build that up from 0 and the answer falls out — and you will see exactly why grabbing the biggest coin first can leave you worse off.

min coins · dp[a] = 1 + min(dp[a−coin]) · greedy fails
dp[a]

Fewest coins that sum to amount a. dp[0] = 0.

THE CHOICE

Try each coin c ≤ a: 1 + dp[a − c]. Keep the smallest.

BUILD UP

Fill amounts 0 → target; each reuses earlier answers.

GREEDY TRAP

Biggest-coin-first is not always optimal — DP is.

coin-change.sim — coins [1,3,4], make 6 with fewest
Ready

The array dp[a] holds the fewest coins to make amount a. dp[0] = 0. Press Step to fill each amount by trying every coin and keeping the smallest.

dp[a] = 1 + min over coins of dp[a − coin]
—
Amount
—
dp value

Small answers build the big one

The brute force tries every combination of coins — exponential. Dynamic programming notices that the best way to make an amount reuses the best way to make a smaller amount. So it fills a one-row table: dp[a] is the fewest coins for a, and to fill it you simply try dropping in each coin and asking how the leftover was best made — a value you already computed. One pass over the amounts, one look at each coin.

01

Base case

dp[0] = 0 — zero coins make zero. Everything else starts as “unreachable”.

02

Try every coin

For amount a, each coin c ≤ a offers 1 + dp[a − c] — one of that coin plus the best for the remainder.

03

Keep the minimum

dp[a] = 1 + min over coins of dp[a − c]. Fill amounts 0 up to the target.

04

Read the answer

dp[target] is the fewest coins; track the chosen coin per cell to reconstruct which coins.

Time
O(amount · coins)
Space
O(amount)
Greedy
not optimal
Class
Unbounded knapsack

Watch amount 6 with coins {1, 3, 4}: greedy grabs the biggest coin, 4, then must add 1 + 1 — three coins. The DP finds 3 + 3 — two coins. A locally biggest choice stranded greedy with an awkward remainder, which is exactly the trap dynamic programming avoids by considering every option. Coin change is really an unbounded knapsack: each coin is an item you may reuse freely.

The picture: every amount borrows from a smaller one

00112231415262728293103+3+3+4 dp[10] = 3: coins 3 + 3 + 4 (greedy: 4 + 4 + 1 + 1 = 4 coins)
Coins {1, 3, 4}, amount 10. Each cell holds dp[a], the fewest coins that make a. The arcs show the chain the answer was built from, following the coin chosen in each cell: 10 came from 7 by adding a 3, 7 came from 4 by adding a 3, 4 came from 0 by adding a 4.

Worked example, step by step

Use coins {1, 3, 4} and amount 10. Start with dp[0] = 0. For each amount a from 1 to 10, try each coin c ≤ a as the last coin: it costs dp[a − c] + 1. Keep the smallest. The three middle columns show those three candidates; “—” means the coin is larger than the amount.

avia coin 1via coin 3via coin 4dp[a]Coin chosen
11——11
22——21
331—13
422114
523221
632323
732223
833224
933331
1043333

The answer is 3, from 3 + 3 + 4. Greedy takes the largest coin first and ends up with 4 + 4 + 1 + 1, which is 4 coins. The trap appears already at amount 6: the 4 coin offers 3 (a 4 plus the best for 2, which is two 1s) while the 3 coin offers 2 (3 + 3). Greedy never looks at the 3-coin option for 6 because 4 is bigger. The table also shows why DP works: every dp[a − c] it reads sits in an earlier cell that is already final. A plain recursion without memoising makes 168 calls for amount 10 on these coins, because the same sub-amounts are recomputed over and over.

Reading the coins back, and counting instead. The last column rebuilds the answer without a second search. Start at 10: the chosen coin is 3, so step to 7. At 7 the chosen coin is 3 again, so step to 4. At 4 it is 4, which reaches 0. The coins are 3, 3, 4. Swap min for addition and the same table answers a different question: how many ways make 10 from {1, 3, 4}? With coins in the outer loop it ends at 8 combinations. With amounts in the outer loop it ends at 64, because 3 + 3 + 4, 3 + 4 + 3 and 4 + 3 + 3 now count as three different sequences. That gap is the loop-order mistake below, on real numbers.

Complexity and trade-offs

CaseTimeSpaceWhy
Bottom-up DPO(amount · k)O(amount)k coin types. One cell per amount, one lookup per coin.
Top-down recursion with memoO(amount · k)O(amount)Same work, plus recursion depth up to amount, which can overflow the stack for large targets.
BFS over amountsO(amount · k)O(amount)Each amount is a node, each coin an edge. The first time you reach the target is the fewest coins.
Plain recursion, no memoexponential in amountO(amount)168 calls for amount 10 with three coins; the count grows exponentially with the amount.
Greedy, largest coin firstO(k)O(1)Optimal only for “canonical” coin systems. Fails on 1, 3, 4.

O(amount · k) is pseudo-polynomial: it depends on the numeric value of the amount, not on the number of digits needed to write it, and the general change-making problem is NP-hard. For ordinary amounts and a few coin types it is instant. For a huge amount with few coins, number-theoretic shortcuts replace the table.

Common mistakes

  • Greedy because it is how change is made in a shop

    For amount 6 with {1, 3, 4} greedy takes 4 + 1 + 1 = 3 coins; the optimum is 3 + 3 = 2. It is safe for systems like US coins, but not in general.

  • Initialising the table with zeros

    Every unreachable amount must start at infinity (or a sentinel). With zeros, min keeps the 0 forever and the program claims amount 6 needs 0 coins.

  • Forgetting to turn “unreachable” into −1

    With sentinel amount + 1, coins [2] and amount 3 leave dp[3] at 4. Returning it directly gives 4 instead of −1. Compare against the sentinel before returning. In C++ or Java an INT_MAX sentinel is worse: INT_MAX + 1 wraps negative and wins the min.

  • Swapping the loop order when counting ways

    Counting combinations needs coins in the outer loop; amounts outer counts ordered sequences. For [1, 2] and amount 3 that is 2 versus 3. The minimum-coins problem is the same for either order, which hides the mistake until you switch to counting.

  • Reading dp[a − c] when c > a

    In Python dp[-2] is a valid index from the end of the list, so a missing c ≤ a guard reads a wrong cell without raising. In C or Java it reads out of bounds.

Where this shows up

  • Currency and cash handling

    Cash dispensers and point-of-sale systems pick denominations; for standard currencies greedy is optimal, and Pearson (2005) gave a polynomial-time test for whether a coin system is canonical, so DP is only needed for odd denominations.

  • Counting ways to make an amount

    The “how many combinations” variant is the classic coin sums problem (Project Euler problem 31 asks it for UK coins). The same table with addition instead of min.

  • Unbounded knapsack and rod cutting

    Coin change is the unbounded knapsack with every item of equal value. Rod cutting, pack-size selection and splitting a payload into allowed block sizes use the same one-dimensional table.

  • Interview staple

    “Coin change” is a standard first dynamic-programming question, usually with the follow-ups of counting ways and returning the actual coins by storing the choice per cell, as the last column above does.

SOLVE IT YOURSELF

Solve it: fewest coins

This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement coin_change(coins, amount): return the fewest coins that add up to amount (each coin usable any number of times), or -1 if it cannot be made. Build up dp[a] = fewest coins for amount a — that is O(amount × coins).

HINTS — 4 IDEAS
  1. Greedy (always take the biggest coin) fails — 6 from {1,3,4} is 3+3, not 4+1+1.
  2. Let dp[a] be the fewest coins to make amount a. dp[0] = 0; start every other entry at infinity.
  3. For each amount a and each coin c ≤ a: dp[a] = min(dp[a], dp[a − c] + 1).
  4. If dp[amount] is still infinity at the end, the amount is impossible → return -1.
CPython · WebAssembly

Check yourself

1 · What does dp[a] store?

Each cell is the optimal coin count for that amount, built from smaller amounts.

2 · Coins {1, 3, 4}, amount 6. Why is greedy wrong?

Taking the biggest coin first strands a bad remainder; DP considers all options and finds 3 + 3.

3 · Coin change is a special case of which problem?

Each coin is an item you can take any number of times — the unbounded knapsack shape.

Questions

When does greedy actually work for coin change?

For canonical coin systems (like US or Euro coins) greedy is optimal. But it is not guaranteed for arbitrary denominations, so DP is the safe general solution. Proving a system is canonical is itself non-trivial.

How do you count the number of ways instead of the fewest?

Change the recurrence to a sum: dp[a] += dp[a − coin], iterating coins in the outer loop to avoid counting permutations. It is the same table with addition instead of a min.

What if the amount is unreachable?

Leave unreachable amounts as infinity; if dp[target] stays infinity, no combination of coins makes it. Interview versions often ask you to return −1 in that case.

Build small, answer big — and skip the greedy trap.

Every amount reuses a smaller one. dp[target] is the fewest coins, guaranteed optimal.

▶  Watch it explained

Coin Change: Greedy Fails, DP Wins

Finished this one? 0 / 99 Algorithms done
NextThe Loaded Bag: 0/1 Knapsack Next on the “DP along one axis” ladder · rung 3 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms