GreedyGreedy
Greedy: When the Local Choice Is Safe
Build a solution by repeatedly taking the locally best choice — correct only when an exchange argument proves that choice never hurts.
a
25
0
10
1
5
2
1
3
taken
·
0
·
1
·
2
·
3
1/17Pay out 6 using the US coin denominations {1, 5, 10, 25}. The greedy rule never changes: repeatedly hand over the largest coin that still fits. Whether that rule is *correct* is a property of the coin system, not of the rule.
Denomination being consideredCoin just takenDenomination finishedToo large to fitWhere the optimal answer differs
PseudocodeLearn Greedy Algorithms →
1greedyChange(coins, target): # coins sorted descending2 taken = []3 for d in coins:4 while target >= d: # take the biggest coin that fits5 taken.append(d); target -= d6 return taken7# ground truth, for comparison — dynamic programming over every amount:8 best[t] = 1 + min(best[t - d] for d in coins if d <= t)Variables
system{1, 5, 10, 25}
remaining6
coinsUsed0
Complexity
best O(n)
avg O(n log n)
worst O(n log n)
space O(1)
Speed