Take the best choice at each step, and prove when that is also the best overall.
You work on the schedule page of a one-day tech festival. Every talk has a start hour and an end hour, and the talks run in different rooms. A visitor can sit in only one talk at a time. Your team lead says: "For each visitor, suggest the most talks they can attend, with no two overlapping."
Here are eight talks. Times are whole hours on a 24-hour clock, so a talk from 10 to 11 uses the hour from 10:00 until 11:00.
| Talk | Starts | Ends |
|---|---|---|
| A | 15 | 17 |
| B | 12 | 16 |
| C | 11 | 15 |
| D | 16 | 19 |
| E | 14 | 18 |
| F | 11 | 12 |
| G | 10 | 11 |
| H | 9 | 14 |
Two talks overlap when they share some time. A talk that starts at 11 can follow a talk that ends at 11, because they only touch at 11. That is allowed.
A set of talks with no overlap is a plan. Your job is to find a plan with as many talks as possible.
The first attempt is correct. Try every set of talks, throw away the sets that contain an overlap, and keep the largest one that is left. With 8 talks there are 2^8 = 256 sets, which is nothing for a computer.
But every extra talk doubles the number of sets. With 40 talks there are 2^40 = 1,099,511,627,776 sets. Even at a million sets a second, that is more than 12 days of work for one visitor. We need a method that does not look at every set.
A cashier must hand back 87 units of change in coins worth 50, 10, 5 and 1. She takes the biggest coin that does not go over the amount left, hands it over, and repeats. First a 50, then three 10s, then a 5, then two 1s. She never takes a coin back.
This is the greedy way of working: at each step, take the choice that looks best by one fixed rule, and never undo it. Each coin she hands over is one choice. The amount still owed is the smaller problem that remains.
The picture is wrong in one way. It hides that the rule can fail. With some coin values, "biggest coin first" hands back more coins than needed. We will see one in the next sections, and that is why each greedy rule needs a reason before you trust it.
A cashier gives change greedily: the biggest coin that fits, handed over for good. The picture fails when that rule hands back too many coins.
A greedy algorithm builds its answer one choice at a time. At each step it applies a fixed rule, takes the choice that looks best right now, and moves on. It never looks ahead and never goes back, so it is fast.
The catch is that a choice that looks best now can lead to a worse answer later. Whether a rule is safe is a question you must answer, and the rest of this lesson shows how.
For the festival, a rule must say which talk to take next. Three rules come to mind: take the talk that starts earliest, take the shortest talk, or take the talk that finishes first. Only one of them is safe.
Predict what happens
Q Talk G runs from 10 to 11, and talk F runs from 11 to 12. Can a visitor attend both?
Answer: B
Two talks overlap only when they share some time. G uses 10:00 until 11:00 and F uses 11:00 until 12:00, so they share none. Touching at 11 is allowed.
Each rule is greedy in the same way. It takes the talk that looks best by the rule, skips any talk that overlaps a talk already taken, and carries on. Only the rule changes. Run them on the eight talks.
| Rule | Talks it takes | Count |
|---|---|---|
| Earliest start first | H (9 to 14), then E (14 to 18) | 2 |
| Shortest first | F (11 to 12), G (10 to 11), A (15 to 17) | 3 |
| Earliest finish first | G (10 to 11), F (11 to 12), B (12 to 16), D (16 to 19) | 4 |
The best plan has 4 talks, and only one rule finds it. Earliest start takes H, a 5-hour talk, and H overlaps G, F, C and B. Shortest first takes A, a 2-hour talk, but A sits across the place where B ends and D begins, so it blocks both. Earliest finish first takes the talk that frees the visitor soonest, so it keeps the most room for the rest.
Sort the talks by end time: G (11), F (12), H (14), C (15), B (16), A (17), E (18), D (19). Keep one number, the end of the last talk taken.
At the start it is 0, because nothing is taken. Go through the sorted talks. A talk fits when it starts at or after that number.
| Talk | Starts and ends | Last end before | Fits? | Last end after | Taken so far |
|---|---|---|---|---|---|
| G | 10 to 11 | 0 | yes: 10 is at least 0 | 11 | 1 |
| F | 11 to 12 | 11 | yes: 11 is at least 11 | 12 | 2 |
| H | 9 to 14 | 12 | no: 9 is before 12 | 12 | 2 |
| C | 11 to 15 | 12 | no: 11 is before 12 | 12 | 2 |
| B | 12 to 16 | 12 | yes: 12 is at least 12 | 16 | 3 |
| A | 15 to 17 | 16 | no: 15 is before 16 | 16 | 3 |
| E | 14 to 18 | 16 | no: 14 is before 16 | 16 | 3 |
| D | 16 to 19 | 16 | yes: 16 is at least 16 | 19 | 4 |
The plan is G, F, B and D. Look at what the sort did. After sorting, "the compatible talk that finishes first" is the next talk in the list that fits.
The sort does the choosing, and one pass over the list does the rest. Many greedy algorithms have this shape: sort by the right key, then scan once.
Sort by end time, then scan once: take a talk when it starts at or after the last end, and skip it otherwise.
Step by step: Earliest finish first on the eight talks. The animated player loads in your browser.
Now watch the rule that fails. Earliest start takes H first, and then nothing that overlaps H can follow.
Step by step: Earliest start first on the eight talks. The animated player loads in your browser.
Predict what happens
Q You have taken G and F, so the last end is 12. The next talk in the sorted list is H, from 9 to 14. What does the rule do?
Answer: B
A talk fits only when it starts at or after the last end. H starts at 9, which is before 12, so it overlaps F and is skipped. The scan goes on to the next talk.
Pick a list of talks and a rule, then step through it forwards and back. The panel at the end shows how many talks the rule took and how many the best plan has.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
A greedy choice is safe when two things hold.
If both hold, you can take the choice, shrink the problem, and repeat. A proof must show the first one. There are two common ways to do it.
After every pick, the talks chosen so far belong to some best plan, and the compatible talk that finishes first is a safe next pick.
Take any best plan, and call its first talk X. Let g be the talk that finishes first of all. Then g ends no later than X. Replace X with g.
The plan is still valid. The next talk in it starts at or after the end of X, which is at or after the end of g, so g does not overlap it. The plan has the same number of talks, so it is still a best plan, and it now starts with g.
So some best plan starts with the greedy choice. Drop every talk that starts before g ends and repeat on the talks that remain. This is an exchange argument: you swap the greedy choice into any best answer and show that nothing gets worse.
The same test shows why earliest start fails. Its first choice is H, so ask whether some best plan contains H.
H runs until 14, so in a plan with H every other talk must start at 14 or later. Those talks are E, A and D, and each pair of them overlaps, so at most one fits. A plan with H has at most 2 talks, while the best plan has 4. No best plan contains H, so the choice is unsafe.
Trying the swap shows the same thing. To put H into the best plan G, F, B and D, you must remove G, F and B, because H overlaps all three. Three talks go out for one, so the plan gets worse.
Write the greedy plan as g1, g2, g3, and so on, in time order. Take any other plan o1, o2, o3, and so on. The claim is: for every number i, g_i ends no later than o_i. The greedy plan stays ahead.
Check it for the eight talks. Another valid plan is G (10 to 11), C (11 to 15) and D (16 to 19), which ends at 11, 15 and 19. The greedy plan ends at 11, 12 and 16. Each greedy end is no later than the matching end: 11 against 11, 12 against 15, 16 against 19.
The reason it always holds:
Now suppose another plan had more talks than the greedy plan, which took k. Its talk number k + 1 would start at or after the end of its talk number k, which is at or after the end of g_k. So it was available when the greedy rule stopped, and the rule would have taken a talk. That is a contradiction, so no plan has more than k talks.
Predict what happens
Q Another valid plan for the eight talks ends its talks at 11, 15 and 19. The greedy plan ends at 11, 12 and 16. What does "stays ahead" say?
Answer: C
At every position the greedy plan has finished no later: 11 against 11, 12 against 15, 16 against 19. A plan that is never ahead cannot have room for an extra talk. The greedy plan here has four talks.
Now a rule with no safe reason. A cashier has coins worth 1, 3 and 4, and must give 6 units with the fewest coins.
"Biggest coin first" takes a 4, leaving 2, then a 1 and another 1. That is three coins. But 3 and 3 is two coins.
| Amount | Greedy coins | Fewest coins |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 1 |
| 4 | 1 | 1 |
| 5 | 2 | 2 |
| 6 | 3 | 2 |
The rule works for every amount from 1 to 5, and fails at 6. Passing a few examples does not show that a greedy rule is safe.
Exercise · Predict the output: Which coins does biggest-first hand over?. The cashier has coins worth 1, 5 and 12 and must give 15 units, biggest coin first. The program prints the coins in the order she hands them over. What does it print?
coins = [1, 5, 12]
left = 15
used = []
for coin in sorted(coins, reverse=True):
while left >= coin:
left -= coin
used.append(coin)
print(*used)The exchange test explains the failure: the best answer for 6 is 3 and 3, and it contains no 4. Putting a 4 in would change the total, so no swap is possible. No best answer contains the greedy choice, so the choice is unsafe.
For the coins 1, 5, 10 and 50, biggest coin first always gives the fewest coins, because each value divides the next bigger one. Here is the reason.
In a best answer, you never use five coins of 1, because one coin of 5 replaces them. You never use two 5s, because one 10 replaces them, and never five 10s, because one 50 replaces them. So all the smaller coins together are worth less than 50.
That makes the number of 50s forced: it is the amount divided by 50, rounded down. The same argument then repeats for the rest. With the coins 1, 3 and 4, the value 3 does not divide 4, and the argument breaks.
Dividing is enough, but it is not needed. With coins 1, 5, 10 and 25, the 10 does not divide the 25, and biggest coin first still always gives the fewest coins. That needs its own proof, and for a new set of coins you check rather than guess.
The lesson is not "greedy is risky". It is "check the rule". The same idea, with a different rule, is safe for one set of coins and unsafe for another.
Biggest coin first fails for coins worth 1, 3 and 4: it gives 4, 1, 1 for six, but 3 and 3 uses fewer coins.
Predict what happens
Q Coins are worth 1, 3 and 4. What is the fewest number of coins that makes 6?
Answer: B
Two 3s make 6. Biggest-coin-first takes a 4 and needs 1 and 1 after it, which is three coins. One counterexample is enough to show a rule is unsafe.
Some greedy algorithms have no choice to make at all. They keep one number up to date.
A bus line has stops 0 to 5. At stop i you may transfer to a shuttle that goes up to hops[i] stops ahead, and any shorter distance too. Can you get from stop 0 to the last stop? Take hops = [2, 3, 1, 1, 0, 4].
Keep farthest, the farthest stop you can reach so far. At each stop i, if i is beyond farthest, you are stuck. Otherwise set farthest to the larger of itself and i + hops[i].
| Stop | hops | Can you be here? | farthest after |
|---|---|---|---|
| 0 | 2 | yes: farthest starts at 0 | 2 |
| 1 | 3 | yes: 1 is at most 2 | 4 |
| 2 | 1 | yes: 2 is at most 4 | 4 |
| 3 | 1 | yes: 3 is at most 4 | 4 |
| 4 | 0 | yes: 4 is at most 4 | 4 |
| 5 | 4 | no: 5 is beyond 4 | stuck |
The last stop cannot be reached. The reason this is safe is that the stops you can reach always form an unbroken run from stop 0 up to farthest.
A shuttle from stop i can stop at any stop up to i + hops[i]. So reaching stop j means every stop between i and j is reachable too. Taking the larger value keeps the run unbroken, and the greedy number never misses a stop.
Exercise · Find the bug: The reach that shrinks. This check says whether you can get from stop 0 to the last stop. It says no for some bus lines where the answer is yes. Which line is wrong?
def can_reach_last(hops):
farthest = 0
for i in range(len(hops)):
if i > farthest:
return False
farthest = i + hops[i]
return TrueHere is interval scheduling as code. most_talks returns the number of talks in a best plan. The step markers [1] to [4] match the steps above.
def most_talks(talks):
# [1] Sort by end time: the talk that finishes first comes first.
order = sorted(talks, key=lambda t: t[1])
# [2] Nothing is taken yet, so the room is free from the start of the day.
free_at = 0
taken = 0
for start, end in order:
# [3] A talk fits when it starts at or after the end of the last talk taken.
if start >= free_at:
# [4] Take it. The visitor is busy until it ends.
taken += 1
free_at = end
return takenpublic int mostTalks(int[][] talks) {
// [1] Sort by end time: the talk that finishes first comes first.
int[][] order = talks.clone();
java.util.Arrays.sort(order, (a, b) -> Integer.compare(a[1], b[1]));
// [2] Nothing is taken yet, so the room is free from the start of the day.
int freeAt = 0;
int taken = 0;
for (int[] talk : order) {
// [3] A talk fits when it starts at or after the end of the last talk taken.
if (talk[0] >= freeAt) {
// [4] Take it. The visitor is busy until it ends.
taken++;
freeAt = talk[1];
}
}
return taken;
}int mostTalks(vector<vector<int>> talks) {
// [1] Sort by end time: the talk that finishes first comes first.
sort(talks.begin(), talks.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
// [2] Nothing is taken yet, so the room is free from the start of the day.
int freeAt = 0;
int taken = 0;
for (auto& talk : talks) {
// [3] A talk fits when it starts at or after the end of the last talk taken.
if (talk[0] >= freeAt) {
// [4] Take it. The visitor is busy until it ends.
taken++;
freeAt = talk[1];
}
}
return taken;
}function mostTalks(talks) {
// [1] Sort by end time: the talk that finishes first comes first.
const order = [...talks].sort((a, b) => a[1] - b[1]);
// [2] Nothing is taken yet, so the room is free from the start of the day.
let freeAt = 0;
let taken = 0;
for (const [start, end] of order) {
// [3] A talk fits when it starts at or after the end of the last talk taken.
if (start >= freeAt) {
// [4] Take it. The visitor is busy until it ends.
taken++;
freeAt = end;
}
}
return taken;
}On the eight talks this returns 4. When two talks end at the same hour, either may come first: both overlap each other, so only one can be taken, and the count is the same.
Now write it yourself. The lab has one function, plan_talks(talks). It returns two numbers: how many talks are in a best plan, and the hour the visitor is done after taking that many talks as early as possible.
The second number follows from the stays-ahead argument. The greedy plan's last end is no later than the last end of any other plan with as many talks, so it is the earliest possible finish. For the eight talks the answer is [4, 19]. For no talks it is [0, 0].
Three rules keep it correct:
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Try every set of talks | Earliest finish: sort, then scan |
|---|---|---|
| Time to choose | O(2^n × n): every set, checked for overlaps | O(n log n) to sort, then O(n) for the scan |
| Steps for 40 talks | about 1.1 trillion sets | about 40 × 5.3 = 213 comparisons to sort, then 40 steps |
| Memory | O(n) for one set at a time | O(n) for the sorted copy |
| Why it is right | Every set is checked | A safe rule: the exchange argument, or staying ahead |
For 100,000 talks, the sort is about 100,000 × 17 = 1.7 million comparisons, and the scan is 100,000 steps. The sort is the expensive part, and the greedy choice itself costs almost nothing.
Use greedy when you can state one rule for the next choice and give a reason it is safe. The reason can be an exchange argument or a stays-ahead argument.
Typical fits are scheduling the most jobs in one room and matching sorted lists, such as servers to jobs. They also include ordering jobs by their deadlines, making change with coins that each divide the next, and tracking how far you can reach.
Words such as "most", "fewest" or "can you reach" are a hint to look for a greedy rule, and a sort often makes the rule obvious. Then prove it, or look for a counterexample.
Do not use greedy when you cannot show the rule is safe, or when a counterexample exists. The coin set 1, 3 and 4 with an amount of 6 is one.
Do not use it when an early choice changes what later choices are worth in ways one rule cannot see. An example is packing a bag where one big item blocks two smaller items that are worth more together. In those cases try every choice with backtracking, or build the answer from smaller answers with dynamic programming, which comes next in this course.
If the input is tiny, the first attempt that tries everything is fine, and it has no proof to get wrong.
order = sorted(talks, key=lambda t: t[0]) looks natural, but it takes H on the eight talks, then E, and stops at 2 talks. The best plan has 4. Sorting by length takes F, G and A: 3 talks. Sort by end time.
Sorting the talks by start time takes the long talk H first and ends with two talks; sorting by end time finds four.
if start > free_at: rejects a talk that starts exactly when the last one ends. On the talks [[9, 10], [10, 11]] it takes only the first one and returns 1. The right answer is 2, because a talk from 10 to 11 can follow a talk from 9 to 10. Use >=.
Writing free_at = end outside the if moves the last end even when the talk was skipped. On [[9, 12], [11, 13], [12, 14]] the talk from 11 to 13 is skipped but the last end still becomes 13, so the talk from 12 to 14 is skipped as well. The result is 1. The right answer is 2: the talks from 9 to 12 and from 12 to 14.
Biggest coin first with coins = [1, 3, 4] is right for every amount from 1 to 5 and wrong at 6. Before you trust a greedy rule, either prove it or look for a counterexample on small inputs with a slow check that tries everything.
Exercise · Break it: Find the amount that biggest-first gets wrong. This cashier takes as many of the biggest coin as fit, then the next, and returns -1 when she cannot make the amount. Coins are positive whole numbers and the amount is 0 or more. Find coins and an amount where she hands over more coins than needed.
def fewest_coins(coins, amount):
left = amount
count = 0
for coin in sorted(coins, reverse=True):
count += left // coin
left %= coin
return count if left == 0 else -1For the fewest shuttle transfers on hops = [2, 3, 1, 1, 4], the rule "take the longest hop" jumps from stop 0 to stop 2, then 3, then 4: three transfers. The best is stop 0, then stop 1, then stop 4: two transfers. The safe rule looks at where each landing stop can reach next, i + hops[i], and not at the length of the hop.
For the fewest transfers, take the landing stop that reaches farthest next, not the longest hop.
Explain the two proofs in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · What greedy means
Q1/2 Which description fits a greedy algorithm?
Answer: B
A greedy algorithm makes one choice at a time with a fixed rule and never undoes it. Trying every choice is the first attempt, and remembering smaller problems is dynamic programming.
Q2/2 Which two things make a greedy choice safe?
Answer: C
A safe choice cannot cost you the best answer, and it leaves a smaller problem of the same kind. Passing a few examples proves neither.
Checkpoint · Interval scheduling
Q1/2 Talks are P from 9 to 12, Q from 11 to 13 and R from 12 to 14. Sorted by end time, which plan does the earliest-finish rule give?
Answer: C
P ends first and is taken. Q starts at 11, before P ends at 12, so it is skipped. R starts at 12, exactly when P ends, so it fits. The plan is P and R.
Q2/2 Why does earliest start first fail on the eight festival talks?
Answer: C
Earliest start takes H, then E, which is 2 talks. The best plan has 4. After H only one of E, A and D can fit, so no best plan contains H. A long talk that starts early can block many short ones.
Checkpoint · Proving a rule safe
Q1/2 In the exchange argument for interval scheduling, why can the first talk of a best plan be replaced by the talk that finishes first?
Answer: C
The replacement ends no later than the talk it replaces, so it cannot overlap the talks that came after. The count stays the same, so the plan is still best.
Q2/2 A greedy plan ends its talks at 11, 12 and 16. Another valid plan ends at 11, 15 and 19. What does "stays ahead" say about them?
Answer: C
Stays ahead compares the plans position by position: 11 against 11, 12 against 15 and 16 against 19. A plan that is never behind cannot lose a talk to the other.
Checkpoint · When greedy fails
Q1/2 Coins are worth 1, 3 and 4. For an amount of 6, biggest coin first gives 4, 1 and 1. What is the fewest coins?
Answer: B
Two 3s make 6. The rule takes a 4 because it is the biggest coin that fits, but no best answer contains a 4, so the choice is unsafe.
Q2/2 Why does biggest coin first work for coins worth 1, 5, 10 and 50?
Answer: C
In a best answer you never use enough small coins to be replaced by one bigger coin. So the smaller coins total less than the biggest, and the count of the biggest coin is forced.
Checkpoint · One number and a sort
Q1/2 A bus line has hops = [3, 0, 0, 1, 2]. A shuttle from stop i goes up to hops[i] stops ahead. Can you reach stop 4?
Answer: B
Keep the farthest stop reached. Stop 0 gives 3. Stops 1 and 2 are at most 3, so you can be there but they add nothing. Stop 3 gives 3 plus 1, which is 4.
Q2/2 What does sorting by end time do for the interval-scheduling greedy?
Answer: C
The sort does the choosing. After it, the scan only needs to ask whether the next talk starts at or after the last end. The cost is O(n log n) for the sort and O(n) for the scan.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.