Skip to content
StackDecode
Dynamic programmingAnimated

Coin Change

Fewest coins for an amount: best of (coins for amount − c) + 1.

Time

O(n · amount)

Extra space

O(amount)

Use it for

Making change, minimum-step problems.

How it works

  1. Find the fewest coins that add up to the amount (or report it is impossible).
  2. Let fewest(x) be the answer for amount x. fewest(0) = 0.
  3. For each x try every coin c ≤ x: fewest(x) = 1 + min over c of fewest(x − c).
  4. Fill x from 1 upwards. O(amount × coins). Note: grabbing the biggest coin first (greedy) can be wrong, e.g. coins 1, 5, 6 for 11 needs 2 coins (5+6), not 6+5×1.

Watch it run

Loading animation…