Part 17 / Topic 13 of 20
Greedy algorithms
A greedy algorithm builds the answer one step at a time, always taking the choice that looks best right now and never backtracking. When that works it is beautifully simple and fast โ but it works only when the local choice provably never hurts the final answer. The skill is not writing greedy code (it is usually the easiest code in this part); it is knowing why this greedy is safe, or finding the counterexample that shows it is not. Think of paying โน672 from a till: grabbing the biggest note that fits (500, then 100, then 50...) feels obviously right โ and with Indian denominations it is. The trap is assuming the same move is right for every coin system.
def greedy_notes(denominations, amount):
notes = []
for note in sorted(denominations, reverse=True):
while amount >= note:
notes.append(note)
amount -= note
return notes
print(greedy_notes([500, 100, 50, 10, 1], 672)) # [500, 100, 50, 10, 10, 1, 1] - 7 notes, optimal
Now the counterexample. Coins (1, 3, 4), amount 6 โ greedy grabs the 4 and is forced into 4+1+1:
print(greedy_notes([1, 3, 4], 6)) # [4, 1, 1] - 3 coins
# but 3 + 3 = 6 in only 2 coins: greedy is WRONG here
The dynamic programming section's coin table confirms the real minimum is 2. One safe, classic greedy โ activity selection: to fit the most meetings in one room, always pick the meeting that ends earliest, because ending earliest leaves the most room for everything after it (that sentence is the proof):
def most_meetings(meetings):
chosen, free_from = [], 0
for start, end in sorted(meetings, key=lambda m: m[1]):
if start >= free_from:
chosen.append((start, end))
free_from = end
return chosen
print(most_meetings([(9, 11), (10, 12), (11, 13), (12, 14), (13, 15)]))
# [(9, 11), (11, 13), (13, 15)] - 3 meetings fit
Real-world example: a conference room's booking system that accepts the request ending soonest serves the most teams per day โ and a wallet app's "fewest notes" button is safe exactly because real currencies are designed so largest-first works.
โ ๏ธ A greedy that passes your three test cases is not proven. Before trusting one, either say out loud why the local choice can never hurt (the activity-selection sentence above), or hunt for a counterexample โ
(1, 3, 4)against 6 is the classic one. When no safe greedy exists, the problem is usually dynamic programming in disguise.
Practice: fewest coins/notes with canonical denominations (and finding the counterexample for weird ones); activity/meeting selection by earliest end; jump-style "furthest reach" problems.
Practice on LeetCode - start here: Assign Cookies ยท Lemonade Change ยท Best Time to Buy and Sell Stock II ยท Jump Game
Show the full practice list (9 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Jump Game II | Medium |
| Gas Station | Medium |
| Hand of Straights | Medium |
| Partition Labels | Medium |
| Valid Parenthesis String | Medium |
| Boats to Save People | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Merge Triplets to Form Target Triplet | Medium |
| Maximum Swap | Medium |
| Candy | Hard |
Full program: examples/13_greedy.py.
Exercise 13: Greedy โ prove it before you trust it
Scenario: A cashier wants the fewest notes for an amount. Largest-note-first feels right โ your job is to show when it is, and when it is not.
What to do: Write greedy_count(denominations, amount) (largest first, using // and %) and fewest_count(denominations, amount) (the honest bottom-up table from the dynamic programming section). Compare them for โน672 with [500, 100, 50, 10, 1] and for amount 6 with [1, 3, 4], printing a verdict line for each.
Sample output:
[500, 100, 50, 10, 1], amount 672: greedy 7, best 7 -> greedy is safe here
[1, 3, 4], amount 6: greedy 3, best 2 -> greedy got it WRONG
Show the solution to Exercise 13
"""Exercise 13: Greedy - prove it before you trust it.
Greedy largest-first is compared against the honest DP answer for two
denomination sets: Indian notes (greedy is safe) and (1, 3, 4), where
greedy picks 3 coins for amount 6 but 2 is possible (3 + 3).
Run: python ex13.py (macOS/Linux: python3 ex13.py)
"""
NOTES = [500, 100, 50, 10, 1]
WEIRD_COINS = [1, 3, 4]
def greedy_count(denominations: list[int], amount: int) -> int:
count = 0
for note in sorted(denominations, reverse=True):
count += amount // note
amount %= note
return count
def fewest_count(denominations: list[int], amount: int) -> int | None:
table = [0] + [None] * amount
for a in range(1, amount + 1):
options = [table[a - d] for d in denominations if d <= a and table[a - d] is not None]
table[a] = 1 + min(options) if options else None
return table[amount]
def main() -> None:
for denoms, amount in [(NOTES, 672), (WEIRD_COINS, 6)]:
greedy = greedy_count(denoms, amount)
best = fewest_count(denoms, amount)
verdict = "greedy is safe here" if greedy == best else "greedy got it WRONG"
print(f"{denoms}, amount {amount}: greedy {greedy}, best {best} -> {verdict}")
if __name__ == "__main__":
main()