Kodewick
Start learning →
Greedy algorithms47 / 50

Greedy algorithms

Lesson 47 of 50 · Part 9 · Algorithm design · about 16 minutes

A greedy algorithm takes what looks best right now at every step and never goes back: it is fast and often right, as when picking the meeting that finishes earliest, but with coins 1, 3 and 4 it makes 6 with 3 coins when 2 will do.

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.c
1#include <stdio.h>2 3int coins[] = {25, 10, 5, 1};4 5void change(int amount) {6    int count = 0;7    printf("%d = ", amount);8    for (int i = 0; i < 4; i++)9        while (amount >= coins[i]) {          // take the biggest that fits10            amount -= coins[i];11            printf("%d ", coins[i]);12            count++;13        }14    printf("(%d coins)\n", count);15}16 17int main(void) {18    change(63);19    change(41);20    change(99);21    return 0;22}
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.c
1#include <stdio.h>2 3int coins[] = {4, 3, 1}, k = 3;4 5int greedy(int amount) {6    int count = 0;7    for (int i = 0; i < k; i++)8        while (amount >= coins[i]) { amount -= coins[i]; count++; }9    return count;10}11 12int best(int amount) {                        // try all: which coin first, then the fewest for the rest13    if (amount == 0) return 0;14    int m = 1000;15    for (int i = 0; i < k; i++)16        if (amount >= coins[i]) {17            int c = best(amount - coins[i]) + 1;18            if (c < m) m = c;19        }20    return m;21}22 23int main(void) {24    for (int a = 1; a <= 10; a++) {25        int g = greedy(a), b = best(a);26        printf("%2d: greedy %d coins, fewest %d%s\n", a, g, b, g == b ? "" : "  <- greedy is wrong");27    }28    return 0;29}
Output
 1: greedy 1 coins, fewest 1
 2: greedy 2 coins, fewest 2
 3: greedy 1 coins, fewest 1
 4: greedy 1 coins, fewest 1
 5: greedy 2 coins, fewest 2
 6: greedy 3 coins, fewest 2  <- greedy is wrong
 7: greedy 2 coins, fewest 2
 8: greedy 2 coins, fewest 2
 9: greedy 3 coins, fewest 3
10: greedy 4 coins, fewest 3  <- 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 <stdio.h>2 3int main(void) {4    int coins[] = {25, 20, 10, 5, 1};5    int amount = 40, count = 0;6    for (int i = 0; i < 5; i++)7        while (amount >= coins[i]) {8            amount -= coins[i];9            count++;10        }11    printf("%d\n", count);12    return 0;13}
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 <stdio.h>2 3int main(void) {4    int coins[] = {25, 10, 5, 1};5    int amount = 63, count = 0;6    for (int i = 0; i < 4; i++)7        while (amount  coins[i]) {8            amount -= coins[i];9            count++;10        }11    printf("%d\n", count);12    return 0;13}

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:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct { char name; int s, e; } Meet;5 6Meet m[] = {{'A', 0, 10}, {'B', 1, 4}, {'C', 4, 7}, {'D', 3, 5},7            {'E', 7, 10}, {'F', 6, 8}, {'G', 10, 12}, {'H', 9, 11}};8int n = 8;9 10int by_end(const void *x, const void *y) {11    const Meet *a = x, *b = y;12    return a->e != b->e ? a->e - b->e : a->s - b->s;13}14int by_start(const void *x, const void *y) {15    const Meet *a = x, *b = y;16    return a->s != b->s ? a->s - b->s : a->e - b->e;17}18int by_len(const void *x, const void *y) {19    const Meet *a = x, *b = y;20    return (a->e - a->s) != (b->e - b->s) ? (a->e - a->s) - (b->e - b->s) : a->s - b->s;21}22 23void pick(const char *rule, int (*cmp)(const void *, const void *)) {24    Meet chosen[8];25    int k = 0;26    qsort(m, n, sizeof(Meet), cmp);27    for (int i = 0; i < n; i++) {28        int ok = 1;29        for (int j = 0; j < k; j++)           // overlapping none of those taken30            if (m[i].s < chosen[j].e && chosen[j].s < m[i].e) ok = 0;31        if (ok) chosen[k++] = m[i];32    }33    printf("%s: %d, ", rule, k);34    for (int j = 0; j < k; j++) printf("%c", chosen[j].name);35    printf("\n");36}37 38int main(void) {39    pick("earliest finish", by_end);40    pick("earliest start ", by_start);41    pick("shortest first ", by_len);42    return 0;43}
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 (that's exactly how this stage's exercise is written).

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 are already sorted by end time. 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.c
1#include <stdio.h>2 3int s[] = {1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12};4int e[] = {4, 5, 6, 7, 9, 9, 10, 11, 12, 14, 16};5int n = 11;6 7int main(void) {8    int count = 0, end = -1;9    // look at each meeting in turn: take it if s[i] >= end10    printf("%d\n", count);11    return 0;12}
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" firstThis stage's exercise

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). The items are already sorted by "value / weight", highest first: 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.c
1#include <stdio.h>2 3int w[] = {10, 20, 30};4int v[] = {60, 100, 120};5int n = 3;6 7double fill(int cap) {8    double total = 0;9    // each item in turn: if w[i] <= cap take it whole (cap goes down); otherwise take cap / w[i] of it, then stop10    return total;11}12 13int main(void) {14    printf("%.1f %.1f\n", fill(50), fill(25));15    return 0;16}
Output
Press Run or Ctrl+Enter

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
  • Huffman, Prim, Kruskal and Dijkstra are all greedy
1qsort(m, n, sizeof(Meet), by_end);2for (int i = 0; i < n; i++)3    if (m[i].s >= end) { count++; end = m[i].e; }