Discrete Mathematics and Combinatorics
Greedy Algorithms and When They Give the Best Answer
Find out when taking the best-looking step each time is provably optimal, using scheduling, coins, codes and spanning trees.
Key takeaways
- A greedy algorithm commits to the locally best choice at each step and never reverses it.
- For scheduling the most non-overlapping activities, choosing the earliest finishing time is optimal, while other natural rules are not.
- Greedy change-making works for United States coins but fails for some other sets of denominations.
- Exchange arguments and "greedy stays ahead" arguments are the two main ways to prove a greedy method correct.
- Structures called matroids are exactly those on which the basic greedy method works for every choice of weights.
A greedy algorithm builds a solution one choice at a time, always taking whatever looks best right now and never going back. Sometimes that produces a perfect answer. Sometimes it fails badly. The way to tell them apart is a proof, because a few successful examples are not enough.
Greedy methods are popular for good reason. They are usually short to describe, quick to run and easy to carry out by hand. The question is always whether an early choice can quietly rule out something better later.
Making change
To give 63 cents with coins of 25, 10, 5 and 1, take the largest coin that fits, again and again: 25, 25, 10, 1, 1, 1. Six coins, and no combination does better.
Now suppose the coins are 4, 3 and 1, and you need 6. Greed takes 4, then 1 and 1, for three coins. The best answer is 3 and 3, two coins. The method did not change. The coin system did.
Whether greed works for a given set of coins has to be checked. For an arbitrary system, dynamic programming finds the fewest coins reliably: compute the best count for every amount from 0 upward, each from earlier ones.
Scheduling a single room
You have requests to use one room, each with a start and finish time, and you want to accept as many non-overlapping requests as possible. Here are six, written as (start, finish):
(1, 4), (3, 5), (0, 6), (5, 7), (8, 9), (5, 9)
Several greedy rules suggest themselves. Two natural ones are wrong.
| Rule | A set of requests that defeats it | What goes wrong |
|---|---|---|
| Earliest start | (0, 10), (1, 2), (3, 4) | takes 1 request, 2 were possible |
| Shortest first | (1, 5), (4, 7), (6, 10) | takes the middle one only, 2 were possible |
| Earliest finish | none exists | always optimal |
With earliest finish on the six requests: sort by finishing time, accept (1, 4), skip (3, 5) and (0, 6) because they overlap it, accept (5, 7), then accept (8, 9), and skip (5, 9). Three requests. Here a meeting may begin the moment another ends.
Proving it: greedy stays ahead
Compare the greedy choices with any other valid schedule, both listed in order of time.
- The first greedy request finishes no later than the first request of the other schedule, because greed picked the earliest finish of all.
- Suppose the kth greedy request finishes no later than the kth other request. Then the other schedule's next request starts after the greedy kth has finished, so it was available to greed too.
- Greed picks the earliest finish among available requests, so its next one also finishes no later.
So greedy never falls behind. If the other schedule had one more request than greedy, that request would still have been available, and greedy would not have stopped. This is induction doing the work.
A small change that breaks it
Give each request a payment and ask for the most money, not the most requests. Take (0, 10) paying 10, (0, 2) paying 1 and (3, 5) paying 1. Earliest finish accepts the two short requests and earns 2. The single long one earns 10.
The proof above fails at once, since it only ever compared how many requests had been accepted. This weighted version is solved by dynamic programming: sort by finish time and, for each request, compare skipping it with accepting it plus the best total from requests that end before it begins. When you adapt a greedy method to a new goal, you must prove it again.
Meeting deadlines
Here is another case where one greedy rule is exactly right. One worker has jobs that each take some time and have a deadline. The aim is to make the worst lateness as small as possible.
| Job | Time needed | Deadline |
|---|---|---|
| A | 3 | 9 |
| B | 2 | 4 |
| C | 4 | 6 |
The rule "earliest deadline first" gives the order B, C, A, finishing at times 2, 6 and 9. Nothing is late. The rule "shortest job first" gives B, A, C, finishing at 2, 5 and 9, so C is 3 units late.
The proof is an exchange. If a schedule runs two neighboring jobs with the later deadline first, swap them. The job moved earlier only benefits. The job moved later now ends when the pair used to end, and because its deadline is the later one, it is no later than the other job was before. So the swap never increases the worst lateness.
Proving it: exchange arguments
The second technique starts with an optimal solution that differs from the greedy one and transforms it, one swap at a time, without making it worse, until the two agree.
Minimum spanning trees are the showcase. Given points and link costs, you want the cheapest set of links that connects everything. Kruskal's method sorts the links by cost and adds each one unless it closes a loop. Suppose an optimal tree lacks the first link greedy chose. Adding that link creates a loop, which contains some other link at least as expensive. Remove it. The result is still a connecting tree and costs no more. Details are in Kruskal's and Prim's algorithms.
Huffman codes
To compress text, you can give common symbols short bit strings and rare ones long strings, making sure no code word is the beginning of another. David Huffman found in the early 1950s that a greedy method gives the best such code.
Repeatedly merge the two least frequent items into a single item whose frequency is their sum. With counts A 5, B 2, C 1 and D 1:
merge C (1) and D (1) → CD (2)
merge B (2) and CD (2) → BCD (4)
merge BCD (4) and A (5) → all (9) Reading the tree from the top, A gets 1 bit, B 2 bits, C and D 3 bits each. The total is 5·1 + 2·2 + 1·3 + 1·3 = 15 bits, compared with 18 bits if every symbol used 2. The ideas behind such limits are in entropy and information.
Matroids: the general theory
Is there a single reason greed works? For a broad class of problems, yes. Suppose you pick items from a collection, and certain sets of items are allowed. Require that any subset of an allowed set is allowed, and that if one allowed set is larger than another, some item from the larger can be added to the smaller while staying allowed.
Such a system is called a matroid. Sets of links without loops form one, and so do sets of linearly independent vectors. The theorem, associated with Richard Rado and Jack Edmonds, says that for a system closed under taking subsets, picking the heaviest allowed item repeatedly gives a maximum-weight set for every assignment of positive weights exactly when the system is a matroid.
The second condition is what protects you. It guarantees that an early choice never leaves you stuck with a smaller set than you could have had.
When greed is only approximate
Many problems are not matroids, yet greed still gives useful guarantees.
- Set cover. To cover all required items with as few groups as possible, repeatedly take the group covering the most uncovered items. The result is within a factor of about ln n of optimal for n items, and doing substantially better is NP-hard.
- Knapsack. Ratio-based greed can be arbitrarily poor, but a small modification guarantees half the optimum, as the knapsack problem shows.
- Traveling salesperson. Visiting the nearest unvisited city often produces a reasonable route with some very bad final legs.
Shortest paths
Dijkstra's method repeatedly settles the unvisited point closest to the start. It is greedy and correct as long as no link has negative length. With a negative link, a point settled early might later be reachable more cheaply, and the commitment fails. See how Dijkstra's algorithm works.
How to test a greedy idea
- State the rule exactly, including how ties are broken.
- Attack it with tiny cases designed to tempt it into a bad first choice.
- If it survives, look for an exchange or stays-ahead proof.
- If the proof stalls at a particular step, build a counterexample from that step.
The most common mistake is to stop after step 2. A rule that survives a dozen hand examples can still fail on the thirteenth.
If you have a computer handy, a cheap middle step is to compare the greedy rule with an exhaustive search on thousands of small random inputs. Any disagreement gives you a concrete counterexample to study. Agreement raises your confidence and still proves nothing about larger cases.
Running time
Most greedy methods spend their effort sorting the candidates or repeatedly finding the best one. Sorting n items takes about n log n steps, and the single pass that follows is often quicker still. A priority queue, a structure that hands back the smallest or largest remaining item efficiently, serves the same purpose when the priorities change as you go, as they do in Huffman's and Dijkstra's methods.
That speed explains why greedy rules are used even where they are not optimal: they give a quick first answer that a slower method can then try to improve.