Algorithms · Visualized
Coin Change (Greedy)
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
To make a target amount using the fewest coins, the greedy approach always picks the largest coin denomination that doesn't exceed the remaining amount. Time: O(n) — n distinct denominations average, O(n) worst; space: O(1).
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Coin Change (Greedy)
GreedyTo make a target amount using the fewest coins, the greedy approach always picks the largest coin denomination that doesn't exceed the remaining amount. This works correctly for 'canonical' coin systems (like standard currency: 1, 5, 10, 25) but can fail to find the true minimum for arbitrary denominations — which is why the general Coin Change problem uses dynamic programming instead.
How Coin Change (Greedy) Works
- Sort the available coin denominations in descending order.
- Starting with the largest coin, use as many of that coin as possible without exceeding the remaining amount.
- Subtract the value used from the remaining amount, and record how many of that coin were used.
- Move to the next smaller denomination and repeat the process.
- Continue until the remaining amount reaches 0 — the collected coins are the greedy solution.
Coin Change (Greedy) Worked Example
Input: {amount: 63, coins: [25, 10, 5, 1]}
Use 25s: 63/25=2 with remainder 13 → use two 25s. Use 10s: 13/10=1, remainder 3 → use one 10. Use 5s: 3/5=0, skip. Use 1s: 3/1=3 → use three 1s. Total coins used: 2+1+0+3 = 6 coins (25,25,10,1,1,1).
def coin_change_greedy(coins, amount):
coins.sort(reverse=True)
count = 0
for c in coins:
count += amount // c
amount %= c
return count if amount == 0 else -1Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Coin Change (Greedy) Time & Space Complexity
When to Use Coin Change (Greedy)
- Everyday cash-register change-making with standard currency denominations.
- A cautionary example showing when greedy algorithms give the correct answer versus when full DP is required (arbitrary coin sets can break the greedy approach).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.