Greedy algorithms
A greedy algorithm takes what looks best right now and never goes back: fast, but not always right, since with coins 1, 3 and 4 it makes 6 from 3 coins instead of 2; interval scheduling by earliest finish, using sort, provably works.
A cashier gives 63 cents in change with 25, 10, 5 and 1 cent coins: two 25s first, 13 left; a 10, 3 left; then three 1s. 6 coins, and that's the fewest possible. This way of working is called greedy: at every step take what looks best right now (the biggest coin that fits), and never go back. It's simple and fast, and often right; but with a different set of coins the same method gives a wrong answer.
Take what looks best right now
1#include <iostream>2#include <vector>3using namespace std;4 5vector<int> coins = {25, 10, 5, 1};6 7void change(int amount) {8 int count = 0;9 cout << amount << " = ";10 for (int c : coins)11 while (amount >= c) { // take the biggest coin that fits12 amount -= c;13 cout << c << ' ';14 count++;15 }16 cout << "(" << count << " coins)\n";17}18 19int main() {20 change(63);21 change(41);22 change(99);23 return 0;24}
63 = 25 25 10 1 1 1 (6 coins) 41 = 25 10 5 1 (4 coins) 99 = 25 25 25 10 10 1 1 1 1 (9 coins)
Now change the coins to 1, 3 and 4. Making 6, greedy takes 4 first, and the 2 left needs two 1s: 3 coins. But 3 + 3 is just 2.
4 + 1 + 13 coinsafter the 4, the 2 left needs two 1s3 + 32 coinsa "smaller" 3 first saves more laterRun every amount from 1 to 10, comparing greedy with the true fewest (trying every way):
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6vector<int> coins = {4, 3, 1};7 8int greedy(int amount) {9 int count = 0;10 for (int c : coins)11 while (amount >= c) { amount -= c; count++; }12 return count;13}14 15int best(int amount) { // try every way: which coin first, then the fewest for the rest16 if (amount == 0) return 0;17 int m = 1000;18 for (int c : coins)19 if (amount >= c) m = min(m, best(amount - c) + 1);20 return m;21}22 23int main() {24 for (int a = 1; a <= 10; a++) {25 int g = greedy(a), b = best(a);26 cout << "make " << a << ": greedy " << g << " coins, fewest " << b << " coins"27 << (g == b ? "" : " ← greedy is wrong") << '\n';28 }29 return 0;30}
make 1: greedy 1 coins, fewest 1 coins make 2: greedy 2 coins, fewest 2 coins make 3: greedy 1 coins, fewest 1 coins make 4: greedy 1 coins, fewest 1 coins make 5: greedy 2 coins, fewest 2 coins make 6: greedy 3 coins, fewest 2 coins ← greedy is wrong make 7: greedy 2 coins, fewest 2 coins make 8: greedy 2 coins, fewest 2 coins make 9: greedy 3 coins, fewest 3 coins make 10: greedy 4 coins, fewest 3 coins ← greedy is wrong
best tries every way, so it's right, but it's exponential (the same amount left over is worked out many times); the next lesson, on dynamic programming, turns it into O(amount × kinds of coin). Greedy only looks at the step in front of it. It works for 25, 10, 5, 1 because that set of coins has a special property, not because "best at each step" by itself guarantees the best overall.
With coins of 25, 20, 10, 5 and 1, how many coins does greedy use for 40?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> coins = {25, 20, 10, 5, 1};7 int amount = 40, count = 0;8 for (int c : coins)9 while (amount >= c) {10 amount -= c;11 count++;12 }13 cout << count << '\n';14 return 0;15}
The coins are 1, 5, 6 and 9, and you need to make 11. How many coins does greedy use? How few will do?
Fill in the comparison in the while: keep taking this coin as long as there is enough for it. The program should print 6 (63 = 25 + 25 + 10 + 1 + 1 + 1).
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> coins = {25, 10, 5, 1};7 int amount = 63, count = 0;8 for (int c : coins)9 while (amount c) {10 amount -= c;11 count++;12 }13 cout << count << "\n";14 return 0;15}
>=. With >, the last 1 can't be taken when 1 is left, and it prints 5; with <=, no coin is ever taken.Interval scheduling: earliest finish first
One meeting room, a pile of requests for the day, each with a start and an end, and only one meeting at a time. How many can it hold at most?
You can think of several "greedy" rules: earliest start first? Shortest first? Earliest finish first? Only the last is always right. The intuition: taking the one that finishes earliest leaves the most time for the rest.
All three rules written out and run on the same meetings. The three differ only in the third argument to sort: a comparator that returns true when a should come before b.
1#include <iostream>2#include <vector>3#include <algorithm>4#include <functional>5#include <string>6using namespace std;7 8struct Meet { char name; int s, e; };9 10vector<Meet> m = {{'A', 0, 10}, {'B', 1, 4}, {'C', 4, 7}, {'D', 3, 5},11 {'E', 7, 10}, {'F', 6, 8}, {'G', 10, 12}, {'H', 9, 11}};12 13void pick(const string& rule, function<bool(const Meet&, const Meet&)> cmp) {14 sort(m.begin(), m.end(), cmp);15 vector<Meet> chosen;16 for (const Meet& x : m) {17 bool ok = true;18 for (const Meet& y : chosen) // overlaps none of those taken19 if (x.s < y.e && y.s < x.e) ok = false;20 if (ok) chosen.push_back(x);21 }22 cout << rule << ": " << chosen.size() << ", ";23 for (const Meet& y : chosen) cout << y.name;24 cout << '\n';25}26 27int main() {28 pick("earliest finish", [](const Meet& a, const Meet& b) {29 return a.e != b.e ? a.e < b.e : a.s < b.s;30 });31 pick("earliest start", [](const Meet& a, const Meet& b) {32 return a.s != b.s ? a.s < b.s : a.e < b.e;33 });34 pick("shortest first", [](const Meet& a, const Meet& b) {35 int la = a.e - a.s, lb = b.e - b.s;36 return la != lb ? la < lb : a.s < b.s;37 });38 return 0;39}
earliest finish: 4, BCEG earliest start: 2, AG shortest first: 3, DFH
"Earliest start" takes A first, running from 0 to 10, and that one meeting eats most of the day; "shortest first" takes D first (only 2 hours long), but D sits right across the join between B and C and shuts both out. Once the meetings are sorted by end time, there's no need to compare with every meeting taken, only with the last one taken: take it if s >= the last one's end (exercise 1).
5 meetings: A [1, 3), B [2, 5), C [3, 6), D [5, 7), E [6, 9). Picking by "earliest finish", which ones are chosen?
n meetings: sort them by end time, then sweep once from the start (each one compared only with the last one taken). What is the whole algorithm's time complexity?
The most meetings
✓The meetings in m are in no order, each a pair {start, end}. First sort them by end time with sort and a lambda, then keep the end time of the last meeting taken in end: if a meeting starts at or after end, take it and update end. Print how many were taken.
4
1#include <iostream>2#include <vector>3#include <algorithm>4#include <utility>5using namespace std;6 7int main() {8 vector<pair<int, int>> m = {{5, 9}, {1, 4}, {8, 12}, {0, 6}, {12, 16}, {3, 5},9 {6, 10}, {2, 14}, {5, 7}, {8, 11}, {3, 9}};10 int count = 0, end = -1;11 // sort by second (the end time), smallest first; then for each meeting: take it if first >= end12 cout << count << '\n';13 return 0;14}
Why "best at each step" needs a proof
Greedy only looks at the step in front of it and never changes a choice. Whether it's right can't rest on "every step feels good"; it needs a proof that choosing this way at the first step doesn't throw the best answer away. The usual way is an exchange argument, which in plain words goes:
- Take any best schedule (one with the most meetings), and look at its first meeting, X;
- Greedy's first is B, the meeting that finishes earliest of all, so B ends no later than X;
- In that best schedule, swap X for B: B ends no later than X, so it can't clash with the meetings after it, and the count is the same, so it's still a best schedule;
- Now the best schedule starts the same way greedy does. Remove B and everything that clashes with it, and what's left is the same problem again; swap step by step the same way, and in the end it's exactly what greedy chose.
So greedy's count is no smaller than any schedule's: it's the most.
Check coins 1, 3 and 4 for 6 the same way: the best is 3 + 3, and greedy's first step takes 4. Swap a 3 for the 4 and the 2 left can't be made with one coin: the swap doesn't go through. Where the exchange fails is where greedy can go wrong. If you can't prove it, try to find a counterexample; once you have one, switch to dynamic programming or backtracking.
In the exchange argument, the first meeting X of a best schedule is swapped for B (the meeting that ends earliest of all). Why can't the swap clash with the meetings after it?
Three meetings: [0, 5), [4, 7), [6, 10). Picking "shortest first", how many do you get? And how many could you actually fit?
Greedy algorithms you've already met
| Algorithm | What it's greedy for at each step | Where |
|---|---|---|
| Huffman tree | Merge the two smallest weights left | Chapter 4 (trees) |
| Prim | Add the vertex nearest to the part already chosen | Chapter 5 (graphs) |
| Kruskal | Take the shortest edge that makes no cycle | Chapter 5 (graphs) |
| Dijkstra | Settle the vertex now nearest to the start | Chapter 5 (graphs) |
| Interval scheduling | Take the earliest-finishing meeting that doesn't clash | This lesson |
| Fractional knapsack (part of an item allowed) | Take the highest "value / weight" first | Exercise 2 |
Each has its own proof. Dijkstra's, for example, needs "no negative edge weights": with a negative edge, the vertex "nearest now" could later be made nearer still by that edge, and the greedy step no longer holds.
In exams: "greedy" is seldom asked about by name; it hides inside questions on Huffman trees, Prim, Kruskal and Dijkstra, where you trace the greedy rule step by step. In interviews the usual ones are interval scheduling (meeting rooms, bursting balloons, non-overlapping intervals), the jump game, and handing out cookies; when you're unsure whether greedy works, try a few small counterexamples first.
Which of these is not a greedy algorithm?
The fractional knapsack
✓Part of an item may be taken (pour out half a bag of rice, say). First sort the items by "value / weight", highest first (compare a.v * b.w > b.v * a.w, no division needed), then take them in turn: take an item whole if it fits, otherwise take the part that fits, then stop. Print the most value for capacities 50 and 25.
240.0 135.0
1#include <cstdio>2#include <vector>3#include <algorithm>4using namespace std;5 6struct Item { int w, v; };7 8double fill(vector<Item> items, int cap) {9 double total = 0;10 // 1. sort by v / w, highest first11 // 2. for each item: w <= cap, take it whole (cap goes down); otherwise take cap / w of it, then stop12 return total;13}14 15int main() {16 vector<Item> items = {{30, 120}, {10, 60}, {20, 100}};17 printf("%.1f %.1f\n", fill(items, 50), fill(items, 25));18 return 0;19}
With the STL
Greedy code mostly comes in two shapes: sort first, then one pass; or at each step take the best one out of a pile. The first is sort with a comparator, the second is priority_queue.
A comparator can be written three ways: a lambda (the usual one), a ready-made function object such as greater<int>(), or an operator< inside the struct. It must be a "strictly less than": when a and b are equal it returns false; writing <= can make sort go wrong, even run off the end of the array.
The same 8 meetings as in the interval scheduling stage, a different question: all of them must happen; how few rooms will do? Sort by start time, and keep a min-heap of when each room frees up: the room on top frees up first; if it is already free (top() <= s), reuse it, otherwise open another.
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5#include <functional>6using namespace std;7 8struct Meet {9 char name; int s, e;10 bool operator<(const Meet& o) const { return s < o.s; } // sorted by start by default11};12 13int main() {14 vector<Meet> m = {{'A', 0, 10}, {'B', 1, 4}, {'C', 4, 7}, {'D', 3, 5},15 {'E', 7, 10}, {'F', 6, 8}, {'G', 10, 12}, {'H', 9, 11}};16 sort(m.begin(), m.end()); // uses operator<17 18 priority_queue<int, vector<int>, greater<int>> rooms; // min-heap: when each room frees up19 for (const Meet& x : m) {20 if (!rooms.empty() && rooms.top() <= x.s) rooms.pop(); // the room free first can take it21 rooms.push(x.e);22 cout << x.name << " " << x.s << "-" << x.e << ": " << rooms.size()23 << " rooms in use, first free at " << rooms.top() << '\n';24 }25 cout << "fewest: " << rooms.size() << " rooms\n";26 27 vector<int> v = {5, 2, 8, 1, 9};28 sort(v.begin(), v.end(), greater<int>()); // largest first29 for (int x : v) cout << x << ' ';30 cout << '\n';31 return 0;32}
A 0-10: 1 rooms in use, first free at 10 B 1-4: 2 rooms in use, first free at 4 D 3-5: 3 rooms in use, first free at 4 C 4-7: 3 rooms in use, first free at 5 F 6-8: 3 rooms in use, first free at 7 E 7-10: 3 rooms in use, first free at 8 H 9-11: 3 rooms in use, first free at 10 G 10-12: 3 rooms in use, first free at 10 fewest: 3 rooms 9 8 5 2 1
The heap never shrinks: reusing a room is a pop then a push; opening a new one is just a push. However many are in the heap at the end is how many rooms were opened. Why this greedy is right: at one moment there are at most 3 meetings going on together (from 4 to 5, A, D and C are all on), so no plan can use fewer than 3 rooms, and this one uses exactly 3.
What's inside: sort is introsort (mostly quicksort, switching to heap sort when the recursion gets too deep, and insertion sort for short pieces), and it is not stable; to keep equal elements in their original order use stable_sort (merge sort). priority_queue is a binary heap on a vector, a max-heap by default; for a min-heap write greater<int>.
| Code | What it does | Cost |
|---|---|---|
sort(b, e, [](const T& a, const T& b) { return …; }) | Sort by your own rule | O(n log n) |
sort(b, e, greater<int>()) | Largest first | O(n log n) |
bool operator<(const T& o) const | What sort, set and priority_queue compare by default | Nothing extra |
priority_queue<int, vector<int>, greater<int>> pq | A min-heap, pq.top() is the smallest | push / pop O(log n), top O(1) |
In interviews: "meeting rooms II" is exactly this stage's program: a sort and a min-heap, O(n log n). "Non-overlapping intervals" and "minimum arrows to burst balloons" both sort by end time and make one pass. Subtracting in a comparator (return a.e - b.e;) is how C's qsort works; C++'s sort wants a bool, so write a.e < b.e.
A priority_queue with greater<int> is a min-heap. After pushing 4 numbers and popping one, what does the program print?
1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6int main() {7 priority_queue<int, vector<int>, greater<int>> q;8 for (int x : {5, 2, 8, 3})9 q.push(x);10 q.pop();11 cout << q.top() << " " << q.size() << "\n";12 return 0;13}
pop removes the 2, and the new top is the smallest of 5 8 3, which is 3, with 3 left. Without greater<int> it is the default max-heap: the top would be 8, and after the pop, 5.Summary
Greedy: take what looks best now, never go back
- Fast and simple, but not always right: coins 1 3 4 for 6, greedy 3 coins, fewest 2
- Interval scheduling by earliest finish always fits the most
- It needs a proof: the exchange argument, swapping the best answer's first step for greedy's without making it worse
- Sort first (the comparator says whether a goes before b) then one pass, or take the best from a priority_queue at each step
1sort(m.begin(), m.end(), [](const Meet& a, const Meet& b) {2 return a.e < b.e;3});4for (const Meet& x : m)5 if (x.s >= end) { count++; end = x.e; }