"Make the locally optimal choice at each step. Interval scheduling, coin change, Huffman."
Loading...
Deep Dive Tutorial
Greedy algorithms make the locally optimal decision at each step without reconsidering past choices. The hard part isn't implementation — it's proving the greedy choice is safe. The most common proof technique is the "exchange argument": assume the optimal solution doesn't make our greedy choice, then show that swapping to our choice doesn't make things worse. If you can prove that, greedy is correct.
lightbulb
Greedy works when: there's a greedy-choice property (local optimal → global optimal) AND optimal substructure. Greedy fails when the best local choice at step k prevents a better global solution — that's when you need DP instead.
Pattern Recognition
Problem Signal
Greedy Strategy
Interval scheduling (max non-overlapping)
Sort by END time, greedily pick earliest-ending
Interval merging
Sort by start time, merge overlapping
Jump game
Track max reachable index, check if target reachable
Meeting rooms (min rooms needed)
Two separate sorted arrays: sort starts + ends
Task with deadlines
Sort by deadline, use max-heap for scheduling
"Minimum operations to achieve X"
Often greedy — pick largest/smallest available each time
Proving greedy correctness — exchange argument: Assume optimal solution picks X. Show you can swap X for the greedy choice without making things worse. If every swap preserves or improves the solution, greedy is optimal.
Greedy fails when: future consequences of a local choice can't be captured locally. Use DP instead.
Greedy sorting tricks: - Interval scheduling: sort by END time (keeps most room for future) - Interval merging: sort by START time (detect overlaps) - Job sequencing: sort by deadline / profit ratio - Two-group problems (candy, tasks): two-pass left→right then right→left