Courses / DSA Patterns for Working Engineers / Chapter 12
Module 4 · Binary search, subsets, greedy, backtracking and DP · Chapter 12 of 39
Greedy Techniques: Safe Local Choices and How to Prove Them
Builds on Intervals: Merging, Inserting and Counting Overlaps and Heaps and Two Heaps: Running Medians and Priority Scheduling. Next up: Backtracking: Choose, Explore, Undo and Prune.
Part 1 · Introduction to greedy techniques
What greedy means
A cashier counts out change by handing over the biggest note that still fits, then repeating with what is left. That habit is a greedy algorithm.
A greedy algorithm builds an answer one step at a time and, at every step, commits to the choice that looks best right now. It never goes back to reconsider. Because nothing is undone, a greedy solution is usually a sort followed by one pass, so it runs in O(n log n) or better and takes a few lines of code.
Backtracking and dynamic programming, which follow in this module, try every choice. A greedy algorithm tries exactly one choice and moves on, which is why it is fast and why it is risky.
"Looks best right now" is a guess about the whole problem, and two properties decide whether the guess is safe.
- Greedy-choice property: some optimal solution contains the choice the rule makes first.
- Optimal substructure: once that choice is made, what remains is a smaller problem of the same kind, and an optimal answer to it completes an optimal answer to the whole.