Kodewick
Start learning →
Greedy algorithms49 / 52

Greedy algorithms

Lesson 49 of 52 · Part 9 · Algorithm design · about 22 minutes

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

main.cpp
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}
Output
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.

Greedy: biggest first4 + 1 + 13 coinsafter the 4, the 2 left needs two 1s
The fewest coins3 + 32 coinsa "smaller" 3 first saves more later
Making 6 from coins 1, 3 and 4: taking the biggest, 4, looks best at the first step, and ends up costing a coin more

Run every amount from 1 to 10, comparing greedy with the true fewest (trying every way):

main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

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 inTap one to fill a blank; tap a blank to take it back

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}

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.

BB1–4
DD3–5
CC4–7
FF6–8
AA0–10
EE7–10
HH9–11
GG10–12
0123456789101112

8 meetings, one a row, already sorted by end time (the moment one ends is free, so the next can start right then). Top to bottom: take it if it doesn't clash with what's taken; the line is where the last one taken ends

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.

main.cpp
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}
Output
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).

Choose one

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?

Choose one

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?

Exercise 1

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.

It should print
4
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter

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:

  1. Take any best schedule (one with the most meetings), and look at its first meeting, X;
  2. Greedy's first is B, the meeting that finishes earliest of all, so B ends no later than X;
  3. 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;
  4. 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.
BB1–4
XX2–5
YY5–8
ZZ8–11
0123456789101112

The exchange argument: a best schedule is X Y Z. Swap the first one, X, for B, the one that ends earliest: Y and Z are untouched and the count stays the same

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.

Choose one

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?

Choose one

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

AlgorithmWhat it's greedy for at each stepWhere
Huffman treeMerge the two smallest weights leftChapter 4 (trees)
PrimAdd the vertex nearest to the part already chosenChapter 5 (graphs)
KruskalTake the shortest edge that makes no cycleChapter 5 (graphs)
DijkstraSettle the vertex now nearest to the startChapter 5 (graphs)
Interval schedulingTake the earliest-finishing meeting that doesn't clashThis lesson
Fractional knapsack (part of an item allowed)Take the highest "value / weight" firstExercise 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.

Choose one

Which of these is not a greedy algorithm?

Exercise 2

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.

It should print
240.0 135.0
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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.

main.cpp
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}
Output
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>.

CodeWhat it doesCost
sort(b, e, [](const T& a, const T& b) { return …; })Sort by your own ruleO(n log n)
sort(b, e, greater<int>())Largest firstO(n log n)
bool operator<(const T& o) constWhat sort, set and priority_queue compare by defaultNothing extra
priority_queue<int, vector<int>, greater<int>> pqA min-heap, pq.top() is the smallestpush / 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.

Guess the outputA wrong guess is fine

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}

Summary

Take-away

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; }