Greedy Coin Change visualization

Repeatedly take the largest coin that still fits — optimal only for some coin systems.

For "canonical" systems like 1, 5, 10, 25, taking the largest coin first always gives the fewest coins.

Edge cases: with coins 1, 3, 4 and amount 6 greedy returns 4+1+1 (3 coins) while 3+3 is optimal; with 2, 5 and amount 3 greedy gets stuck although no solution exists anyway. Compare with the DP version.

Complexity

Time: best O(k), average O(k + A/c), worst O(A). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure greedyChange(coins, A):
  sort coins descending
  for c in coins:
    while A ≥ c:
      take c; A ← A − c
  if A > 0: greedy failed to reach the amount
  return taken coins

More greedy algorithms