01The greedy idea
A greedy algorithm builds the answer one step at a time, and at every step takes the option that looks best right now. It never reconsiders: a choice once made is final.
That makes greedy algorithms short and fast, usually a sort plus one pass, O(n log n). The catch is that "best right now" is not always "best overall". A greedy algorithm is correct only when two things hold:
- Greedy-choice property: some optimal answer starts with the greedy choice.
- Optimal substructure: after that choice, what remains is a smaller copy of the same problem.
So greedy is never "obviously right". You pick a rule, then you either prove it or break it with a counterexample.