29 of 32 · 6 min
Taking the best option now
Some problems are solved by a rule so simple it feels like cheating: at every step, take whatever looks best right now, and never reconsider.
That is a greedy algorithm. When it works it is fast and short. When it does not it is confidently wrong, and telling the two apart is the skill.
When it works
You have meetings with start and end times and want to attend as many as possible.
The rule: sort by end time, and repeatedly take the next meeting that starts after the last one you took.
def max_meetings(meetings):
meetings.sort(key=lambda m: m[1])
count, finish = 0, 0
for start, end in meetings:
if start >= finish:
count += 1
finish = end
return countWhy finishing earliest is the right rule: whichever meeting you take first, taking the one that ends soonest leaves at least as much room for everything else. You can swap any optimal solution's first meeting for this one without losing anything. That argument is called an exchange argument, and it is what a proof of a greedy rule looks like.
When it fails
Make 30 from coins of 25, 10 and 1.
Greedy takes 25, then five 1s: six coins. The best answer is three 10s. The first choice foreclosed the better option and greedy never reconsiders.
With the usual Indian or American coin systems greedy happens to be correct, which is exactly why this is dangerous: it works on every example you try casually, and fails on a set you were not given.
| Problem | Greedy? |
|---|---|
| Meetings, most attended | yes, by earliest end |
| Coins, arbitrary denominations | no, needs a table |
| Fractional knapsack | yes, by value per weight |
| 0/1 knapsack | no, needs a table |
| Minimum spanning tree | yes, Kruskal and Prim |
The test to apply
Can a choice that looks best now make a better overall answer impossible?
Fractional knapsack: no, because the last item is cut to fit exactly and nothing is wasted. 0/1 knapsack: yes, because an item taken can leave a gap nothing fills.
If the answer is yes, greedy is wrong and the tool is dynamic programming, which is exactly the machinery for trying the options you cannot choose between.