DSA Master › Topic 15
Greedy Algorithms
A greedy algorithm makes the locally best choice at each step and never revisits it. It works only when you can argue that the local choice never hurts the global answer, usually with an exchange argument. When greedy breaks, the problem is often DP.
Concepts
- Greedy choice
- Sorting
- Interval scheduling
- Local vs global optimum
How to recognise it
- Sorting by one key and scanning once seems to give the answer.
- You track a running "farthest reach" or a running balance.
- A quick counterexample doesn't break the greedy rule.
Common pitfalls
- Look for a counterexample before you trust a greedy rule.
- Candy needs two passes, left-to-right then right-to-left.
Problems
- Jump Game (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Maximum Units on a Truck (Easy)
- Partition Labels (Medium)
- Candy (Hard)
- Hand of Straights (Medium)
- Maximum Length of Pair Chain (Medium)