Greedy algorithms
Make the best-looking choice now, never take it back, and move on. When you can show that choice is always safe, one pass gives the best answer, often right after a sort.
One safe choice at a time, never undone
A greedy algorithm builds its answer one step at a time. At each step it takes the option that looks best right now, the greedy choice, and never revisits it. There is no search over alternatives and no backtracking, so it is usually a sort followed by a single O(n) pass.
The catch is that "looks best now" is often wrong. Paying 6 with coins 1, 3 and 4, taking the largest coin first gives 4 + 1 + 1, three coins, while 3 + 3 needs two. So a greedy solution comes with a reason it is safe. The usual one is an exchange argument: take any best answer that differs from yours at the first choice, swap your greedy choice into it, and show the result is no worse. If that always works, some best answer starts with your choice, and the same reasoning covers every step after it.
The rule
Use a greedy algorithm only when you can say why the greedy choice can always be part of a best answer. If you can't, test it on a small counterexample before trusting it.
Sorting reveals an order where the cheapest or tightest item goes first
Match items from two lists, as many pairs as possible
Sort both; pair the smallest item that works with the smallest that needs it
"Can you reach the end?" or "fewest steps" with jump lengths
Track only the farthest point you can reach so far
Choose the most non-overlapping events
Sort by end time; always keep the one that ends first
Each item must satisfy rules about its neighbors
Satisfy one side in a left-to-right pass, the other in a right-to-left pass
A small counterexample beats the obvious rule
Not greedy: try dynamic programming instead
Give each cookie to the least greedy child it can satisfy
Each child needs a cookie of at least a certain size, and each cookie goes to one child at most. Sort both lists. Take the cookies from smallest up: if a cookie is big enough for the least demanding child still waiting, give it to that child. If it isn't, no one else can use it either, since everyone left needs more, so skip it.
The exchange argument: in any best answer, the smallest useful cookie could be handed to the least demanding child instead, and no child loses out. So the greedy pairing is as good as any.
Keep only the farthest cell you can reach
Each cell holds the longest jump you may take from it. Can you get from the first cell to the last? Trying every sequence of jumps explodes. The greedy view needs one number: the farthest cell reachable so far. Every cell up to it is reachable too, so walk left to right, stretching that number. If you ever stand past it, you are stuck.
The zeros are not traps as long as an earlier cell jumps over them. The greedy choice here is not a jump at all: it is the decision to remember only the reach, which is all that matters for the question.
Two passes, each fixing one side
Children stand in a row with ratings. Each gets at least one candy, and a child rated higher than a neighbor must get more than that neighbor. Find the fewest candies. One pass can't see both neighbors at once, so split the rule: a left-to-right pass makes every child beat a lower-rated left neighbor, then a right-to-left pass fixes the right neighbors, keeping the larger of the two counts so the first pass is not undone.
Each count is the smallest that satisfies its rule, and taking the larger of the two satisfies both, so no child gets more than necessary. Two O(n) passes in all.
Sort, then take or skip in one pass
- 1items ← sorted by the key that makes the greedy choice come first
- 2answer ← empty
- 3for each item in items
- 4 if item can be added without breaking a rule
- 5 add item to answer
- 6 else
- 7 skip item
- 8return answer
Before writing it, name the key and say why the item that comes first under it is safe to take. Most greedy bugs are a wrong key: by start time instead of end time, by size instead of size per unit.
Where greedy solutions go wrong
Coins 1, 3 and 4 for 6: largest first gives three coins, the best is two. When a small counterexample breaks the rule, the problem usually needs dynamic programming.
For the most non-overlapping events, sorting by start time or by length fails; sorting by end time works. Test the key on three or four hand-made cases.
A rule about both neighbors needs two passes, or a careful argument that one is enough.
If the solution needs to go back and change earlier choices, it is not greedy any more: it is search, and its cost is no longer one pass.
3 questions
Remember this
- A greedy algorithm takes the best-looking choice at each step and never revisits it: usually a sort and one pass.
- Trust it only with a reason, usually an exchange argument; a small counterexample, like coins 1, 3 and 4 for 6, means dynamic programming instead.
- Most greedy bugs are a wrong sort key: name the key and say why the item that comes first under it is safe to take.
Now solve some yourself
Only this topic 0 of 11 solved
- EasyMake change at a lemonade stand
- EasyFewest taxis for groups of up to four
- EasyFewest notes to pay an amount
- EasyLoad a truck with the most units
- EasyFlip signs k times for the largest sum
- MediumProfit from every rising day
- MediumFewest jumps to the last cell
- MediumWhere to start a trip around a fuel loop
- MediumSend people to two cities at the lowest cost
- MediumRebuild a queue from heights and counts
- HardFewest numbers to add so every sum is possible
Mixed with topics you have practiced 0 unlocked
6 more once you have practiced Basic sorting, Hash tables & maps, Heaps & priority queues, Merge intervals. Play one of its examples to the end and solve one of its problems to unlock them.
Problems open on their own sites (LeetCode, Codeforces, CodeChef, AtCoder, CSES) in a new tab. Tick Solved when you get it accepted there; your ticks decide which mixed problems open next.
Next