Algorithms
Coin Change (Minimum Coins)
O(amount × number of coin types) time — for every amount, you check every coin once · O(amount) space for the table.
The idea, in plain English
This is the honest way to make change. It takes no shortcuts, and never assumes the biggest coin is always the smart pick. For every amount from 1 up to the target, you ask: what is the fewest coins that make exactly this much, built from answers you already worked out for smaller amounts? By the time you reach the target amount, you have genuinely tried every combination, not just the greedy-looking one.
How it works
- 1Make a table where table[amount] holds the fewest coins needed to make that exact amount. Start table[0] at 0, since zero coins make zero amount, and mark everything else as 'not yet known'.
- 2For every amount from 1 up to the target, try each coin. If the coin fits, check whether 'one more coin' plus the best answer for the remaining amount beats what is currently in the table.
- 3After you fill the whole table, table[target] holds the answer — or a sign that it is impossible, if no combination of coins can reach that exact amount.
When you'd use it
Use it to make exact change with coin systems that do not work well with the greedy approach, or for any 'fewest steps to reach an exact total' problem — real currency systems, token or resource costs, or the minimum moves in a game where each move has a fixed cost.
Common beginner mistakes
- Trusting the greedy approach, always grabbing the biggest coin, to give the true minimum. With coins like [1, 3, 4], greedy on amount 6 grabs a 4 then two 1s, for 3 coins total, while the true best is 3 + 3, for 2 coins. Only this table-based approach is guaranteed correct.
- Forgetting to handle the impossible case. If no combination of coins reaches the exact amount, that table cell should stay marked unreachable, not silently show a wrong number.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Amount: 6
Coins available: 1 3 4
Minimum coins needed: 2
Amount: 3
Coins available: 2 5
Minimum coins needed: -1See it in motion
Ready. Fill the table amount by amount, one coin at a time.
Not sure this is the right topic? See the learning paths → or where this leads →