When greedy works: the exchange argument
1 The best choice now, and when it fails
A greedy algorithm builds its answer one choice at a time. At each step it takes the choice that looks best right now, and it never goes back to change it. The danger is that a choice can look best now and still be wrong.
Making change shows both sides. With rupee coins of 1, 2, 5 and 10, the greedy way works: take the biggest coin that fits, again and again. For 18 rupees, that gives 10 + 5 + 2 + 1, and no way uses fewer than four coins.
A country has coins of 1, 3 and 4, and we need to make 6. The biggest coin that fits is 4. That leaves 2, and only 1s fit:
The 4 looked best, and it cost a coin later. So a greedy rule needs a reason before we trust it. The usual reason is the exchange argument, and the rest of this lesson builds it on one problem.
2 Assign Cookies: a rule to prove
Our running example is Assign Cookies. Each child has a greed: the smallest cookie that makes them content. A cookie fits a child when its size is at least the child's greed. Each child gets at most one cookie, and we want as many content children as we can get.
A sensible person starts with the child who is easiest to please. The child of greed 2 is happy with cookie 3, 4 or 6. Giving them the 6 would waste it, because a greedier child may need it. So the greedy rule is:
- Take the least greedy child left.
- Give them the smallest cookie that fits.
- A cookie too small for this child is too small for everyone left, so throw it away.
On our example, the children of greed 2, 3 and 5 get cookies 3, 4 and 6. Cookie 1 fits nobody, and nothing is left for the child of greed 8, so three children are content. The 4 coin also sounded right, so the next section proves this rule.
3 The swap
We do not compare greedy with every possible plan. We take one best plan, whatever it is, and change it until it matches greedy, without ever making it worse.
In the drawings, the top row is the children, sorted by greed. Under each child is the cookie they get, and a dash means none. Greedy's plan stays on the left. On the right is another plan that also makes three children content:
The swap is safe because of two facts:
- Cookie 4 fit the child of greed 2. Cookie 3 is the smallest cookie that fits that child, so 4 is at least 3.
- Cookie 3 fit the child of greed 3 in the best plan.
So cookie 4 fits the child of greed 3 as well. Both children stay content, the count stays at 3, and the best plan now starts the way greedy does.
4 The exchange argument
The swap did not depend on our numbers. The child greedy serves first is A, and greedy's cookie for A is c. A best plan that differs gives A some cookie d, and gives c to a child B. The same chain holds:
So swapping c and d keeps both children content. Two other cases are easier:
- Nobody holds c. A takes c in place of their own cookie.
- B holds c, and A has nothing. c moves from B to A, and the count stays the same.
So some best plan starts with greedy's first choice. Without that child and that cookie, the rest is the same problem, one child smaller, and the same swap works again. In the end, a best plan makes every choice greedy made, so greedy's count is the best count.
Every exchange argument has these four steps:
- Take any best answer.
- If it differs from greedy's first choice, swap greedy's choice in.
- Show the answer is no worse.
- Repeat on what is left.
Step 3 is where a wrong rule breaks. For 6 with coins 1, 3 and 4, the best answer is 3 + 3. Putting greedy's 4 in place of a 3 leaves 2 to make, which takes 1 + 1. That is three coins, so the swap makes the answer worse, and greedy is wrong there.
5 The algorithm, traced and coded
We sort both arrays, so the least greedy child and the smallest cookies come first. Then we walk the cookies from the smallest. content counts the content children, and it is also the index of the least greedy child still waiting:
- The cookie fits
greed[content]. That child takes it, andcontentmoves on. - It does not fit. It fits nobody left, so we skip it.
Sorted, the greeds are [2, 3, 5, 8] and the sizes are [1, 3, 4, 6]:
| cookie size | greed[content] | fits? | content |
|---|---|---|---|
| 1 | 2 | no | 0 |
| 3 | 2 | yes | 1 |
| 4 | 3 | yes | 2 |
| 6 | 5 | yes | 3 |
The cookies run out with content at 3, and the child of greed 8 never gets a turn. The answer is 3.
C++
sort changes the caller's vectors. That is fine here. Copy them first if the caller needs the original order.
Arrays.sort on an int[] sorts numbers in place, smallest first. No comparator is needed.
sort() works in place and returns None. Use sorted(greed) when you need a new list instead.
Always pass (a, b) => a - b. Without it, sort compares numbers as text, so [10, 9] stays [10, 9], and the walk gives wrong answers.
sort.Ints sorts in place, smallest first. slices.Sort does the same in newer Go.
The arrays come in as mut values, so sort can reorder them. content is a usize to index greed, and becomes an i32 only at the end.
Array.Sort sorts in place, smallest first, and changes the caller's arrays.
Cost. The two sorts take O(n log n + m log m) for n children and m cookies, and the walk is one pass after them. At 10⁵ of each, that is a few million steps. Scanning every cookie for each child instead would be about 10¹⁰ steps, so it gets TLE. Besides the sort, the walk needs one counter, O(1) extra space. Most greedy solutions cost the same way: an O(n log n) sort, then an O(n) pass.
6 Stays ahead: Jump Game
Jump Game shows a second way to prove a greedy rule. Each value is the longest jump we may take from that index. We start at index 0 and ask whether we can reach the last index.
A rule that sounds right is to jump as far as we can each time. On [2, 3, 1, 0, 4] it gets stuck:
The greedy that works walks left to right and keeps reach, the farthest index any jump seen so far can land on. At index 0, reach is 0 + 2 = 2. At index 1, it becomes 1 + 3 = 4, the last index, so the answer is yes.
The proof is that greedy stays ahead: no plan of jumps ever gets past reach. A jump from index i lands at most at i + nums[i], and reach already counts it. Every index up to reach can be reached, because a jump may be shorter than its value. So when the walk comes to an index past reach, no plan lands there, and the answer is no:
Jump Game II asks for the fewest jumps. Counting the reach one jump at a time stays ahead of every plan there too.
7 Mistakes and edge cases
- Trusting a rule because it sounds right. "Take the biggest coin" and "jump as far as you can" both fail. Try to break a rule on three or four values first.
- Sorting one side the wrong way. If the cookies go largest first, the walk gives the biggest cookie to the least greedy child. On greed
[1, 5]and cookies[1, 6], the 6 goes to the child of greed 1, and the 1 fits nobody else. The answer is 2, but this gives 1. - A strict comparison where ties count. A cookie of exactly the child's greed is enough. With
>instead of>=, greed[3]and cookies[3]give 0 instead of 1. - Overflow in totals. Many greedy answers add up what was chosen, such as the value in a knapsack. 10⁵ values of 10⁹ add up to 10¹⁴, far past a 32-bit
int, so keep totals in a 64-bit type.
8 Greedy or dynamic programming?
The knapsack shows the line between the two. A bag holds weight 10, and three items are on the table:
| item | weight | value | value per unit |
|---|---|---|---|
| A | 6 | 30 | 5 |
| B | 5 | 20 | 4 |
| C | 5 | 20 | 4 |
In the fractional knapsack, we may take part of an item. Greedy takes the best value per unit first: all of A for 30, then 4 units of B for 16, so 46. The swap works, because a unit of a worse item can always trade places with a unit of a better one.
In the 0/1 knapsack, each item goes in whole or not at all. The same rule takes A, and then B no longer fits, so it gets 30. B and C together get 40. The swap fails, because taking A changes what fits later. The 0/1 version needs dynamic programming, in a later lesson.
A problem is likely greedy when:
- One local rule decides each step, often after a sort by the right key.
- No choice needs undoing, because it never blocks a better choice later.
- A swap or stays-ahead argument works on a small example.
When choices interact and a small counterexample breaks the rule, think of dynamic programming. When the rule needs the best item still open, a heap from the binary heaps lesson finds it in O(log n). The next lesson, on intervals, chooses between sorting by start and by end.
Practice it
- Jump GameMedium
- Jump Game IIMedium
- Gas StationMedium
- Partition LabelsMedium
- Hand of StraightsMedium
- Merge Triplets to Form Target TripletMedium
- Valid Parenthesis StringMedium
- CandyHard
- Assign CookiesEasy
- Lemonade ChangeEasy
- Fractional knapsackMedium
- Fewest coins with greedyEasy
- Shortest job firstMedium
- Job sequencingMedium
- Minimum Number of Arrows to Burst BalloonsMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.