Greedy algorithms: pick what looks best right now

When you give change, you grab the biggest coins first. When you book a meeting room, you put in the meeting that ends first. Taking what looks best at each step is called greedy. It is fast and simple, but it is not always right. Step through it and compare when it works and when it fails.

Short answer. A greedy algorithm takes the one thing that looks best at each step, and never undoes a choice. It follows a single path, so it is fast. But it is not always right. Whether it works comes down to one question: "Is the best-looking choice right now part of a best overall answer?" If you find even one example where it goes wrong, that greedy algorithm is wrong.

Press "Next" to go one step at a time. Each coin takes two steps. ① Compare: a two-headed arrow joins the amount left and a coin, and a sum like 500 ≤ 760 appears at the top right. The biggest coin that fits turns orange, and coins too big for what is left are faded and crossed out. ② Pay: the picked coin moves along an arrow to the coins paid row, and a subtraction like 760 − 500 = 260 appears at the top right. The coins paid row (green) is what greedy has paid so far. The bottom row (blue) is the fewest coins, found by checking every case. If greedy uses more, the last step draws the missing places in the bottom row as dashed circles and writes something like "1 more". The amount goes from 10 to 2000 (in steps of 10) for "500, 100, 50, 10" and from 1 to 30 for "4, 3, 1".

Try this. ① The starting amount 760 ends with five coins: 500, 100, 100, 50, 10. Each coin takes two steps, compare and pay, so that is 10 steps. The fewest coins in the bottom row is also 5. ② Press "4, 3, 1" and the amount becomes 6. Greedy takes 4, 1, 1, which is 3 coins, but the fewest is 3 + 3, which is 2 coins. ③ With the same coins, set the amount to 10. Greedy takes 4 + 4 + 1 + 1 (4 coins), and the fewest is 4 + 3 + 3 (3 coins). ④ With "500, 100, 50, 10" the two rows always have the same number of coins. The self-check on this page compares every amount from 10 to 2000 in steps of 10 to confirm it.

Definitions

The text below explains in plain words. These are the textbook definitions. Here a problem means finding, among the answers that keep the rules, the one with the smallest or largest value (an optimization problem).

optimal solution
In an optimization problem, a solution that keeps all the rules and has the best value of the objective function: the smallest for a minimization problem, the largest for a maximization problem. There can be more than one optimal solution.
greedy algorithm
An algorithm that builds a solution one step at a time. At each step it picks the one thing that looks best at that moment by a set rule (the greedy choice), and it never takes back a choice. If there is even one input where a greedy algorithm does not give an optimal solution (a counterexample), that greedy algorithm does not guarantee an optimal solution for the problem.
greedy-choice property
The property that there is at least one optimal solution that contains the greedy choice made at a step. If it holds at every step, you can make the greedy choice and solve the smaller problem that is left the same way, and you get an optimal solution.
coin change problem
Given coin values c1,c2,…,cm and an amount A, use as few coins as possible whose values add up to A. xi is the number of coins of value ci. Greedy (largest coin first) is right for some coin sets and wrong for others. To make 6 from 4, 3, 1, greedy gives 4 + 1 + 1, which is 3 coins, while the optimal solution is 3 + 3, which is 2 coins.

min∑i=1mxi(∑i=1mcixi=A, xi∈{0,1,2,…})

activity selection problem
Given n activities (meetings), each with a start time si and a finish time fi, pick as many activities as possible that do not overlap. Two activities i and j do not overlap when the condition below holds. Greedy that picks the activity that finishes first gives an optimal solution.

fi≤sj∨fj≤si

1. What greedy means: take the best thing now and never look back

A greedy algorithm solves a problem in steps. Each step does three things.

1. Among the things not yet looked at, take the one that looks best by a fixed rule
2. If adding it breaks no rule, add it. Otherwise throw it away
3. Go back to 1 until everything is looked at. Never look again at what you added or threw away

For change, the rule for "best" is "the biggest coin that fits in what is left", and the limit is "never go over what is left". For the meeting room, "best" is "ends earliest" (experiment ② lets you try other rules), and the limit is "do not overlap a meeting already in".

Greedy does not look ahead. It does not ask what the choice will lead to later, and it never goes back to try another path. That is why it is fast. The meeting room problem is done after one sort and one pass from the top. For the same reason, it can be wrong. If an early choice blocks the way to a better answer, greedy never notices.

2. Follow it by hand

Take the starting values of experiment ①: make 760 with the coins 500, 100, 50, 10.

PickLeft to payBiggest coin that fits (why)Left after taking itCoins taken so far
1760500 (500 ≤ 760)760 − 500 = 260500
2260100 (500 > 260, skipped; 100 ≤ 260)260 − 100 = 160500, 100
3160100 (500 > 160, skipped; 100 ≤ 160)160 − 100 = 60500, 100, 100
46050 (500, 100 > 60, skipped; 50 ≤ 60)60 − 50 = 10500, 100, 100, 50
51010 (500, 100, 50 > 10, skipped; 10 ≤ 10)10 − 10 = 0500, 100, 100, 50, 10

That is 5 coins. Even checking every case, you cannot do it with fewer than 5. For these coins and this amount, greedy was right.

Now make 6 with the made-up coins 4, 3, 1.

  1. 6 left: the biggest coin that fits is 4. 2 left.
  2. 2 left: 4 and 3 are too big, so take 1. 1 left.
  3. 1 left: take 1. 0 left. Greedy's answer is 4 + 1 + 1, 3 coins.

But 3 + 3 needs only 2 coins. The moment the first step took 4, the biggest-looking coin, the 2 that was left could only be filled with 1 + 1. Greedy never goes back, so it cannot fix this.

Greedy (biggest coin first) Fewest coins 6210630 − 4− 1− 1− 3− 3 3 coins 2 coins
Making 6 from 4, 3, 1. Each box is the amount left, and the number above each arrow is the coin paid in that step. Greedy pays 4 first, so the 2 left has to be filled with 1 + 1 (3 coins). Paying 3 twice takes only 2 coins.

3. Problems where greedy works, and where it fails

One question decides whether greedy works. "Is the choice that looks best right now part of at least one best overall answer?" If it is, taking it and solving the smaller problem that is left the same way loses nothing. If this holds at every step, greedy is right to the end. When you make 6 from 4, 3, 1, the first choice 4 is not part of the best answer 3 + 3. That is why it failed.

The next experiment asks the same question about a meeting room. There is one room and 8 made-up meetings. We want to fit as many as we can without overlaps. Try changing the rule for picking.

Each meeting, in the lined-up order, takes two steps. ① Compare: the meeting looked at now gets a thick orange border and a "now" arrow, and the closest meeting already in (or the one it overlaps) gets a dashed orange border. Dashed vertical lines drop from the end of the meeting that starts first and the start of the other, and below the chart it says "no overlap" when end ≤ start and "overlap" when end > start. ② Decide: with no overlap it gets a green fill and says "in"; with an overlap it is faded and says "overlap". A meeting that starts exactly when another ends does not overlap it. When two meetings tie on the rule (for example, the same length), the one that starts first comes first.

Try this. ① "Ends earliest first" puts in B, C, E, F, H, which is 5. Checking every case (all 256 groups), the most that fit is also 5. ② "Starts earliest first" puts in the long meeting A first, because it starts at 9:00. A holds the room until 13:30, so B, C, D and E all stay out, and you get 3 (A, F, H). ③ "Shortest first" puts in the one-hour meetings D and G first, but D overlaps both C and E, and G overlaps both F and H. You get 3 (D, G, B).

Now ask the question. If you put in A, the first choice of "Starts earliest first", you can fit at most 3, because only F, G and H do not overlap A. If you put in D, the first choice of "Shortest first", you can fit at most 4. Both left the best answer (5) at the very first step. The first choice of "Ends earliest first", B, is part of the best answer B, C, E, F, H.

"Ends earliest first" was right for the input on this page, and it is known that this rule gives the most meetings for any list of meetings. As a rough feeling: putting in the meeting that ends first leaves the most time after it. This page does not cover the proof of why it is always right.

One wrong example means that greedy algorithm is wrong

Once you have a greedy algorithm, you either prove it is right or find an example where it goes wrong (a counterexample). A hundred examples that come out right are not a proof. "Shortest first" can be right on a day when the meetings are spread far apart. But if there is even one example like D and G, a short meeting that sits across two others, that rule is wrong. An easy way to find such an example is to make small inputs and compare with the answer from checking every case. The self-check on this page does this for all 200 amounts with "500, 100, 50, 10".

4. Key properties

PropertyIn plain wordsIn the experiments
Never goes backOnce something is added or thrown away, it is never looked at againAfter taking 4 for the amount 6, it cannot fix it
FastIt follows one path. The meeting room takes one sort and one pass8 meetings are each looked at once (the experiment splits each into compare and decide, 16 steps)
Not always rightWhat looks good now can cost you overall6 with 4, 3, 1, and "Shortest first"
Whether it works depends on the problem and the ruleMaking change depends on the coins, and the meeting room depends on the ruleTwo coin sets, three rules
Right needs a proof, wrong needs one exampleMany examples that come out right are not a proof. One wrong example is enoughThe self-check's 200 comparisons

5. In code

def greedy_change(amount, coins):
    taken = []
    for coin in sorted(coins, reverse=True):   # biggest coin first
        while amount >= coin:
            taken.append(coin)
            amount -= coin
    return taken

def most_meetings(meetings):                  # list of (start, end)
    picked, last_end = [], float("-inf")
    for start, end in sorted(meetings, key=lambda m: m[1]):   # ends earliest first
        if start >= last_end:                 # starting right when one ends is fine
            picked.append((start, end))
            last_end = end
    return picked

greedy_change(6, [4, 3, 1]) returns [4, 1, 1]. The greedy rule lives in the single line with sorted(..., key=...). To change the rule, change only the key (key=lambda m: m[0] means starts earliest first). The Python standard library has no greedy function as such.

6. Which one to use when

MethodWhat it doesTime (best · typical · worst)Extra memoryGood · bad · when to use
GreedyTakes the one best thing at each step and never goes backMeeting room: O(n log n) in all three. Sorting is most of it, so twice the meetings take a bit more than twice as longRoom for what it picked, O(n)Fast and short. Can be wrong. Use it on problems where it is known to work (meeting rooms, minimum spanning tree, Dijkstra)
Dynamic programmingWrites the answers to all the smaller problems in a table, then picks the best answer for the big problem from themMaking change: O(amount × number of coin types) in all three. Twice the amount takes twice as longOne cell per amount, O(amount)Solves even the change problems where greedy fails. The table can get big. Use it when small answers combine into the big answer
BacktrackingTries every path, but gives up early on paths that cannot workMeeting room: worst O(2ⁿ), so one more meeting doubles it. Much less when many paths are cut earlyThe one path being followed, O(n)Always right. Becomes impossible as the input grows. Use it on small inputs, or to test a greedy answer

Big O notation is covered on the time complexity page. n is the number of meetings. The "most possible" on this page comes from the simplest method: looking at all 256 (2⁸) groups of the 8 meetings.

Where it is used

Frequently asked questions

How do I know if a greedy algorithm is right?

You need a proof. Running many examples that all come out right is not a proof. The other way around, one example where it goes wrong is enough to show the greedy algorithm is wrong. Comparing it with a method that checks every case on small inputs is an easy way to find such an example. The self-check on this page does exactly that.

Does greedy always work for the coins 500, 100, 50, 10?

The code on this page checked all 200 amounts from 10 to 2000 (in steps of 10), and greedy always matched the fewest coins. Amounts outside that range, and a proof, are not covered here. If the coins change, you have to check again. Some coin sets, like 4, 3, 1, fail right away at the amount 6.

How is greedy different from dynamic programming?

Greedy follows one path only. Dynamic programming writes down the answers to all the smaller problems and picks the best among them. To make 6 from 4, 3, 1, dynamic programming tries each coin 4, 3, 1 once and looks at the answers for what is left, 2, 3 and 5 (2, 1 and 2 coins). The smallest is 1 coin for 3, so with one more coin of 3 the answer is 2 coins. Greedy uses 4 and only looks at the 2 that is left.

Words

Words used hereWhat books call it
Taking what looks best right nowgreedy algorithm
The thing picked at each stepgreedy choice
The best overall answeroptimal solution
The choice now is part of a best answergreedy-choice property
An example where it goes wrongcounterexample
Checking every caseexhaustive search, brute force
Making changecoin change problem
Fitting the most meetings into one roomactivity selection, interval scheduling
Lines that connect every point as short as possibleminimum spanning tree (MST)

Sources

← Minimum spanning treesDynamic programming →