Builds onSorting as a tool
01The idea
A greedy algorithm builds the answer one step at a time, and at each step takes the choice that looks best right now. It never goes back to change an earlier choice. That makes greedy solutions short and fast. Most are a sort followed by one pass.
The catch is that the best-looking step is not always part of the best answer. A greedy algorithm is only correct when you can show that the local choice is safe. The usual argument is an exchange. Take any best answer that made a different choice, swap in the greedy choice, and show the answer is still at least as good. If that swap always works, the greedy choice never hurts.
A classic failure shows why the check matters. Make 6 cents from coins of 1, 3 and 4, using the fewest coins. Greedy takes the biggest coin first: 4, then 1, then 1. That is three coins. But 3 + 3 uses two. For this kind of question you need dynamic programming instead.
Most greedy algorithms start by sorting. The sort order is the greedy rule: smallest first, earliest end first, highest value per weight first.
02How to spot it
Try greedy when:
- the problem asks for the most or the fewest of something, such as matches, meetings, jumps or coins
- there is a natural order to handle items in, such as by size, deadline or end time
- once an item is handled, it never matters again
Before you trust it, try to break it. Build a small input where the greedy choice looks good but leads to a worse total. If you find one, switch to dynamic programming. If every attempt fails, write down the exchange argument.
Common greedy rules that are known to work:
- To fit the most non-overlapping intervals, take the one that ends first.
- To match small items with needs, give each item to the smallest need it covers.
- To reach the end of a jump list, track the farthest index you can reach so far.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue