Greedy Algorithms

A greedy algorithm takes the choice that looks best now and never takes it back. On these 11 talk requests, booking the talk that ends first fits 5 talks. Booking the one that starts first fits only 3.

Pick a rule and watch it book the hall. Then we build, piece by piece: the scan, the proof that it is safe, where greedy breaks, Huffman codes, coins, matroids and graphs.

You need sorting, a little Python, and the idea of dynamic programming (CLRS Chapter 15). We build the rest from zero.

Based on Chapter 16 of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. It follows Chapter 15, Dynamic Programming. The explanations, toys and devices are our own.

Book the hall with one rule

Eleven made-up requests. The best possible count, 5, comes from checking all 2,048 subsets. Ties go to the earlier start.

Chapter 0

Pack the Hall: Which Rule Wins?

Try three tempting rules on small inputs and watch each one lose

You run one lecture hall. Eleven speakers ask for it on the same day, each for a fixed time. Two talks that overlap cannot both happen. You want to book as many talks as you can.

This is the activity selection problem: from a set of time intervals, choose the largest set where no two overlap. Activity i runs from its start si up to its finish fi. The finish moment itself is free, so a talk can start the moment another ends.

A greedy algorithm builds its answer one choice at a time. It takes the choice that looks best now and never takes it back. The hard part is the rule for "best".

Spring the trap

Each trap is a small day built to beat one rule. Pick a trap, then switch between the tempting rule and earliest finish.

Made-up days. On the fewest-conflicts trap, the small number at the right of each bar is how many other talks it overlaps.

RuleIts trapRule booksBest
Shortest first[0, 5), [4, 7), [6, 11)12
Earliest start[0, 10), [1, 3), [4, 6), [7, 9)13
Fewest conflicts11 talks in the device34

The rule that works: book the talk that finishes first. Then repeat on the talks that start after it ends. It uses up the least of the day, so it leaves the most time for the rest.

A worked number, on the first trap. The short talk [4, 7) overlaps both others, so shortest first books 1 talk. Earliest finish takes [0, 5), then [6, 11): 2 talks.

The failure. Symptom: a scheduler passes your hand tests but books fewer talks on real days. Measure: on random days of up to 15 talks, compare it with brute force over all subsets. Fix: change the rule. One counterexample is enough to reject a greedy rule.

The road

  1. Activity selection: sort by finish, scan once.
  2. The exchange argument: why earliest finish is safe.
  3. The knapsack test: where greedy works and where it needs DP.
  4. Huffman codes: merge the two rarest letters.
  5. Huffman is optimal: the proof, and the entropy floor.
  6. Coin change: break the cashier's rule.
  7. Matroids: task scheduling and the theory under greedy.
  8. Greedy on graphs: Kruskal, Dijkstra, set cover.
  9. Field guide: the numbers, the code, the credit.
Talks [0, 10), [1, 3), [4, 6) and [7, 9) want the hall. How many can you book at most?

Chapter 1

Activity Selection: Sort Once, Scan Once

Step the earliest-finish scan and watch one clock decide every talk

Earliest finish turns into a short program. Sort the activities by finish time. Walk the list once. Keep each activity that starts at or after the finish of the last one you kept.

One test decides each activity. Call the activity you look at am, with start sm. Call the last activity you kept ak, with finish fk.

Say it aloud

s-m is at least f-k.

sm
s-m the start time of the activity we look at now.
≥
is at least greater than or equal. Equal counts, because the finish moment is free.
fk
f-k the finish time of the last activity we kept. The code calls it last_finish.
In plain words

If the new activity starts no earlier than f-k, keep it and move f-k to its finish. If it starts earlier, skip it. f-k only moves forward.

With numbers

The last kept activity A finishes at 4, so f-k = 4. D starts at 5: 5 is at least 4, so keep D and set f-k = 7. E starts at 3: 3 is less than 7, so skip E.

  1. Sort the activities by finish time.
  2. Keep the first one. Set last_finish to its finish.
  3. For each next activity, apply the test. Keep it and update last_finish, or skip it.

Step the scan

The rows run in finish order. Press Step. The warm line is last_finish; blue is the activity under test.

These are the eleven activities CLRS uses in Section 16.1, named A to K in finish order.

The worked number. The scan keeps A [1, 4), D [5, 7), H [8, 11) and K [12, 16). A brute-force search over all 2,048 subsets finds no set of 5, and four different sets of 4. Greedy finds one of them with 11 tests.

The cost is the sort, about n log n steps, plus n tests. For 50 activities, brute force would check 250 subsets, about 1.1 × 1015.

The failure. Symptom: a talk that ends at 4 and a talk that starts at 4 are never booked together. Measure: print the test. Fix: use "at least" (≥), not "greater than". The intervals are half-open, so touching is not overlapping.

The activities are [1, 3), [2, 5), [4, 7), [6, 9) and [8, 10), already in finish order. What does the scan keep?

Chapter 2

The Exchange Argument: Why Earliest Finish Is Safe

Swap the greedy choice into any best answer and see that nothing breaks

Picking the earliest finisher now might seem to block a better plan later. The exchange argument shows it never does. Take any best answer. Swap the greedy choice into it. Show the swap keeps it legal and no worse.

Two facts make a greedy algorithm correct:

Name the pieces. Let O be any largest set of compatible activities. Let ak be the activity in O that finishes first. Let a1 be the activity that finishes first of all: the greedy choice.

Say it aloud

O-prime equals O without a-k, together with a-1.

O′
O-prime the new set after the swap.
O
O any optimal set of non-overlapping activities.
− {ak}
minus a-k remove a-k, the activity in O that finishes first.
∪ {a1}
union a-1 add a-1, the activity that finishes first of all.
In plain words

Remove a-k from O and put a-1 in its place. O-prime has the same size as O. It has no overlap: a-1 finishes no later than a-k, and every other activity in O starts after a-k finishes.

With numbers

O = {B, D, I, K} is optimal. Its first finisher a-k is B [3, 5). The greedy choice a-1 is A [1, 4). The next activity in O, D, starts at 5, and A ends at 4. So O-prime = {A, D, I, K}: still 4 activities, still no overlap.

Swap until O is greedy

The top track is greedy's set. The bottom track is an optimal set O. Press Swap to replace the first activity where they differ.

The same eleven CLRS activities as Chapter 1. These three sets and greedy's A D H K are the only optimal sets.

Then repeat on the rest. After a1, the activities that start at f1 or later form a smaller copy of the problem. Induction on the number of picks finishes the proof: every greedy pick is safe.

The failure. Symptom: you trust a rule because it worked on five examples. Measure: try to write the swap. Which element of O do you replace, and why is the result legal and no worse? Fix: if no swap works, hunt for a counterexample, like the traps of Chapter 0.

In the proof, why can a-1 replace a-k in O without an overlap?

Chapter 3

The Knapsack Test: Greedy or Dynamic Programming?

Fill one bag two ways and see the same rule win once and lose once

A thief has a bag that holds 50 kg. Three items are in the room. The greedy rule: take the item with the most value per kilogram first.

ItemWeightValueValue per kg
A10 kg$60$6
B20 kg$100$5
C30 kg$120$4

There are two versions. In the fractional knapsack, you may take part of an item, like gold dust. In the 0/1 knapsack, you take a whole item or none, like gold bars.

Fill the bag three ways

Each row is the bag. Slide the capacity. Teal is what greedy takes, pale teal a part of an item, purple the best whole-item choice.

50 kg

The items are the CLRS example of Section 16.2. The page finds the best 0/1 choice by checking all 8 subsets.

The worked number at 50 kg. Fractional greedy takes all of A ($60, 40 kg left), all of B ($100, 20 kg left), then 20 of C's 30 kg: $120 × 20/30 = $80. Total $240, and the bag is full. The 0/1 greedy takes A and B for $160 and leaves 20 kg empty, because C does not fit. The best whole-item choice is B and C: $220.

Why the difference? In the fractional case the exchange argument works one kilogram at a time. Any kilogram of a cheaper item can swap for a kilogram of a richer one. Whole items cannot swap a kilogram at a time.

The 0/1 version needs dynamic programming. Let K[i][w] be the best value using only the first i items in a bag of capacity w. Item i weighs wi and is worth vi.

Say it aloud

K of i and w equals the larger of K of i minus 1 and w, and v-i plus K of i minus 1 and w minus w-i.

K[i][w]
K of i and w the best value from items 1 to i in a bag of w kg.
max
the larger of keep whichever option is worth more.
K[i−1][w]
K of i minus 1 and w leave item i: the best from the first i − 1 items, same bag.
vi
v-i the value of item i, in dollars.
K[i−1][w − wi]
K of i minus 1 and w minus w-i take item i: the best from the rest in the room it leaves. Allowed only if w-i is at most w.
In plain words

For item i, try both choices. Leave it, and the answer is K[i−1][w]. Take it, and you gain v-i but have only w − w-i kg for the first i − 1 items. Keep the larger.

With numbers

With items A, B, C and w = 50: K[2][50] = 160 (A and B) and K[2][20] = 100 (B). So K[3][50] = max(160, 120 + 100) = 220.

The table has n × W cells, so the work is about n times W. That is pseudo-polynomial: polynomial in the number W, but not in the number of digits needed to write W.

The failure. Symptom: a packing tool leaves space empty and misses a better set. Measure: run the DP on the same items and compare. Fix: if items cannot be split, use the DP. Keep greedy only for items that can be split.

Items (weight, value): A (5, 10), B (4, 40), C (6, 30), D (3, 50). The bag holds 10 kg, whole items only. What does greedy by value per kg get?

Chapter 4

Huffman Codes: Merge the Two Rarest

Build the code tree from the bottom up and count the bits it saves

A file holds 100,000 letters from an alphabet of six. A fixed code gives each letter 3 bits: 300,000 bits. But a appears 45,000 times and f only 5,000. Give a a short codeword and f a long one, and the file shrinks.

A prefix code gives no letter a codeword that begins another letter's codeword. Then a decoder reads bits left to right and always knows where a letter ends. Every prefix code is a binary tree: letters sit at the leaves, a left edge is 0, a right edge is 1.

Huffman's algorithm (David Huffman, 1952) builds the best such tree:

  1. Make a leaf for each letter, weighted by its frequency. Put all leaves in a min-priority queue.
  2. Take out the two nodes with the lowest frequency.
  3. Join them under a new node. Its frequency is their sum. Put it back.
  4. Repeat until one node is left. It is the root.

Build the Huffman tree

Press Step to merge the two rarest nodes. Blue marks the pair taken out; teal nodes are merges. When one tree is left, the codes appear.

The six-letter set is the CLRS example of Section 16.3, in thousands. Ties go to the node made first, so other valid trees exist with the same cost.

How good is a tree? Call the frequency of letter c c.freq. Call its depth in tree T, which is its codeword length, dT(c). The cost B(T) is the number of bits for the whole file.

Say it aloud

B of T equals the sum over letters c of c-freq times d-T of c.

B(T)
B of T the total bits to encode the file with tree T.
Σc
the sum over c one term for each letter of the alphabet.
c.freq
c-freq how many times letter c appears in the file.
dT(c)
d-T of c the depth of c's leaf in T, which is the length of its codeword in bits.
In plain words

For each letter, multiply c-freq by the length of its codeword. Add these products. Frequent letters near the root keep B(T) small.

With numbers

abracadabra has a 5, b 2, r 2, c 1, d 1. The tree gives a 1 bit and the others 3 bits. B(T) = 5 × 1 + 2 × 3 + 2 × 3 + 1 × 3 + 1 × 3 = 23 bits. A fixed 3-bit code needs 11 × 3 = 33 bits.

A shortcut: B(T) also equals the sum of every merged frequency, 2 + 4 + 6 + 11 = 23. Each merge adds one bit to every letter under it. For the CLRS six letters, B(T) is 224,000 bits against 300,000.

The cost of the build: n − 1 merges, each with a few heap operations of about log n steps. Total about n log n for an alphabet of n letters.

The failure. Symptom: the decoder outputs garbage after the first letter. Measure: check whether any codeword is the start of another. Fix: put letters only at leaves, and read every code off the tree.

Frequencies are A 3, B 3, C 1, D 1, E 1. What does the first merge join?

Chapter 5

Why Huffman Is Optimal, and How Close to Entropy

Prove the merge is safe, then measure the gap to the floor no code can beat

The proof has the same two parts as Chapter 2.

  1. Greedy choice. Let x and y be the two rarest letters. Some optimal tree has x and y as sibling leaves at the deepest level. If a more frequent letter sat deeper than x, swapping the two would not raise the cost.
  2. Optimal substructure. Replace x and y by one new letter z, with frequency x.freq + y.freq. A best tree for the smaller alphabet gives a best tree for the full one.

The second part rests on one count. Let T be a tree for the full alphabet with x and y as sibling leaves. Let T′ be the same tree with that pair replaced by the single leaf z.

Say it aloud

B of T equals B of T-prime plus x-freq plus y-freq.

B(T)
B of T the bits for the file with the full tree.
B(T′)
B of T-prime the bits with x and y merged into one letter z.
x.freq
x-freq how often the rarest letter x appears.
y.freq
y-freq how often the second rarest letter y appears.
In plain words

x and y sit one level below where z sits. So each of their x-freq + y-freq appearances costs one more bit. Nothing else changes. A cheaper T-prime would give a cheaper T, so a best T-prime gives a best T.

With numbers

In abracadabra, merge c and d into z with frequency 2. The best tree for a 5, b 2, r 2, z 2 costs 21 bits. Add 1 + 1 and get 23 bits, the Huffman cost.

How low can any code go? Claude Shannon's entropy is the floor. Let pc be the probability of letter c: its count divided by the total.

Say it aloud

H equals minus the sum over c of p-c times log base 2 of p-c.

H
H the entropy: the fewest bits per letter any prefix code can average.
−Σc
minus the sum over c one term per letter. The minus makes the result positive, because each log is negative.
pc
p-c the share of the file that is letter c, from 0 to 1.
log2 pc
log base 2 of p-c minus the ideal codeword length for c. A letter with p-c = 1/4 deserves 2 bits.
In plain words

Give each letter its ideal length, log base 2 of 1 over p-c. Weight each length by p-c and add. No prefix code averages fewer bits than H. Huffman's average L is always less than H + 1.

With numbers

abracadabra: H = 0.455 × 1.14 + 2 × 0.182 × 2.46 + 2 × 0.091 × 3.46 = 2.04 bits per letter. Huffman's L = 23 / 11 = 2.09. The gap is 0.05 bits.

Measure the gap to entropy

Four letters. Slide how common a is; b, c and d share the rest in the ratio 2 : 1 : 1. Watch Huffman's average L stay between H and H + 1.

50%

Made-up probabilities. The page runs Huffman's algorithm live for each setting.

At 50% the probabilities are 1/2, 1/4, 1/8 and 1/8. Each ideal length is a whole number, so L = H = 1.75 bits. Push a to 95% and H falls to 0.36 bits, but a still needs 1 whole bit, so L is 1.075 bits.

The failure. Symptom: Huffman barely shrinks a file where one letter is 95% of the text. Measure: compare L with H. For two letters at 95% and 5%, H = 0.29 bits but L = 1 bit. Fix: code blocks of letters together, or use arithmetic coding, which is not limited to whole bits per letter.

Four letters each have probability 1/4. What are H and Huffman's L?

Chapter 6

Coin Change: Break the Cashier's Rule

Pick a coin set and an amount, and find every amount where greedy pays too many coins

Make change for an amount with the fewest coins. The cashier's rule is greedy: take the largest coin that fits, then repeat on what is left.

Find where greedy overpays

Choose a coin set and slide the amount. The strip below shows every amount from 1 to 40; red cells are amounts where greedy uses more coins than needed.

6

The fewest coins come from the dynamic program below, run live. We made up the coin sets other than US coins.

With US coins 25, 10, 5 and 1, the strip has no red cell. With 4, 3 and 1, the rule fails at 6: greedy pays 4 + 1 + 1, three coins, but 3 + 3 is two.

The greedy-choice property fails here. No swap turns the best answer {3, 3} into an answer that contains a 4. A coin set where greedy is always right is called canonical. US coins are canonical; 4, 3, 1 is not. You check this. You do not guess it.

The fix is a dynamic program. Let C[a] be the fewest coins that make amount a, with C[0] = 0. Let c stand for one coin value.

Say it aloud

C of a equals 1 plus the minimum, over coins c no larger than a, of C of a minus c.

C[a]
C of a the fewest coins that make amount a.
1
one the last coin we use.
minc ≤ a
the minimum over coins c no larger than a try every coin that fits as the last coin and keep the cheapest.
C[a − c]
C of a minus c the fewest coins for what is left after coin c.
In plain words

Try each coin c as the last coin. It costs 1, plus the best way to make a − c. Keep the cheapest. Fill C from 0 upward, so every C[a − c] is ready when you need it.

With numbers

Coins 4, 3, 1: C[2] = 2, C[3] = 1, C[5] = 2. So C[6] = 1 + min(C[2], C[3], C[5]) = 1 + min(2, 1, 2) = 2. The winning last coin is 3.

The failure. Symptom: a change machine gives three coins where two would do. Measure: run greedy and the DP for every amount up to a few hundred and list where they differ. Fix: use the DP, which costs the amount times the number of coin values.

Coins are 8, 5 and 1. How many coins does greedy use for 10, and how many are needed?

Chapter 7

Matroids: Task Scheduling and the Theory Under Greedy

Schedule seven tasks by penalty and see the structure that makes greedy exact

Seven tasks each take one hour on one machine. Each task has a deadline and a penalty you pay if it finishes late. Which tasks should run on time?

The greedy rule: take tasks in order of penalty, highest first. Keep a task if all kept tasks can still finish on time. Put it in the latest free hour at or before its deadline.

Schedule by penalty

Press Step. The top row is hours 1 to 7. Each task tries its deadline hour, then earlier hours. A task with no free hour is late.

The tasks are the CLRS example of Section 16.5: deadlines 4, 2, 4, 3, 1, 4, 6 and penalties 70, 60, 50, 40, 30, 20, 10.

How do we know a set can finish on time? For a set A of tasks, let Nt(A) be the number of tasks in A with deadline t or earlier.

Say it aloud

N-t of A is at most t, for every t from 1 to n.

Nt(A)
N-t of A how many tasks in the set A are due by hour t.
≤
is at most less than or equal.
t
t an hour; also the number of one-hour tasks that can finish by then.
t = 1, …, n
every t from 1 to n check each hour; n is the number of tasks.
In plain words

By hour t, only t one-hour tasks can finish. So the tasks due by t must number at most t. If this holds for every t, run the set in deadline order and every task is on time.

With numbers

The kept set {a1, a2, a3, a4, a7} has deadlines 4, 2, 4, 3, 6. N-2 = 1, N-3 = 2, N-4 = 4, N-6 = 5: all fine. Add a5 (deadline 1) and N-4 = 5, more than 4. So a5 is late. The late tasks are a5 and a6: penalty 30 + 20 = 50.

Why is greedy exact here? The on-time sets form a matroid: a family of "independent" sets with two rules.

CLRS proves that on any matroid with weights, greedy by weight finds a heaviest independent set. The forests of a graph form a matroid too, which is why Kruskal's algorithm works (Chapter 8).

The 0/1 knapsack is not a matroid. Take a 10 kg bag. A = {one 10 kg item} and B = {two 5 kg items}. B is larger, but neither of its items fits next to A. The exchange rule fails.

The failure. Symptom: scheduling by earliest deadline lets a big penalty go late. Measure: compare the total penalty with a brute-force search on small cases. Fix: order by penalty and test each set with Nt.

Greedy has kept {a1, a2, a3, a4} (deadlines 4, 2, 4, 3). Why is a5, with deadline 1, rejected?

Chapter 8

Greedy on Graphs: Trees, Paths and Covers

Step Kruskal's algorithm and see the same exchange idea in later chapters

A town wants to link six buildings with cable. Each possible link has a cost. Every building must be reachable, and the total cost must be as low as possible.

That is a minimum spanning tree: edges that connect every node of a weighted graph, with no cycle and the least total weight. Kruskal's algorithm sorts the edges by weight. It keeps each edge that does not close a cycle.

Step Kruskal

Press Step to test the next lightest edge. Teal marks a kept edge. A grey dashed edge would close a cycle, so Kruskal skips it.

A made-up graph with nine edges of distinct weights 1 to 9.

The worked number. Kruskal keeps DE (1), CF (2), BE (3), AB (4) and BC (5). Five edges join six nodes, so the tree is complete, with total weight 15. AD (6) would close the cycle A, B, E, D, so Kruskal skips it.

The exchange argument here is the cut property. Split the nodes into two groups. The lightest edge between the groups belongs to some minimum spanning tree. If a tree left it out, adding it makes a cycle that crosses the split twice. Drop the other crossing edge, which is no lighter, and the tree gets no heavier.

ProblemGreedy ruleExact?CLRS chapter
Minimum spanning treeLightest edge that closes no cycle (Kruskal)Yes, by the cut property23
Shortest pathsFinish the closest unfinished node (Dijkstra)Yes, if no edge weight is negative24
Set coverPick the set that covers the most uncovered itemsNo; at most about ln n + 1 times the best35

The failure. Symptom: Dijkstra returns a wrong distance. Take edges S→A 2, S→B 3 and B→A −2. Dijkstra finishes A at distance 2, but S, B, A costs 1. Measure: compare with Bellman-Ford. Fix: use Bellman-Ford when weights can be negative.

Kruskal reaches edge CE (7). C and E are already connected through kept edges. What happens?

Chapter 9

Field Guide

Keep the terms, the numbers, the code and the checks in one place

A greedy algorithm commits to the best-looking choice and never looks back. It is exact when the problem has the greedy-choice property and optimal substructure. The exchange argument is how you prove the first. A counterexample is how you disprove it.

TermMeaningNumber to remember
Activity selectionSort by finish, keep each activity that starts at or after the last finish.CLRS 11 activities: A, D, H, K
Greedy-choice propertySome optimal answer contains the greedy choice.proved by one swap
Optimal substructureThe rest is a smaller copy whose best answer completes the whole.induction on picks
Fractional knapsackTake by value per kg; split the last item.$240 at 50 kg
0/1 knapsackWhole items; needs DP.greedy $160, best $220
Huffman codeMerge the two rarest nodes until one is left.abracadabra: 23 bits, fixed 33
Entropy HThe floor on average bits per letter.H ≤ L < H + 1
Canonical coinsCoin sets where largest-first is always right.4, 3, 1 fails at 6
MatroidHereditary sets with the exchange rule; greedy by weight is exact.tasks: penalty 50
KruskalLightest edge that closes no cycle.n − 1 edges

Check before you trust a greedy algorithm

  1. State the rule in one sentence: what you sort by, and what you keep.
  2. Write the swap: which element of an optimal answer the greedy choice replaces, and why the result is legal and no worse.
  3. Check that what is left is a smaller copy of the same problem.
  4. Brute-force every small input (up to about 12 items) and compare.
  5. Watch the edges: equal times, ties, one item, an empty input.

The core, in code

pythonimport heapq
from itertools import count

def select_activities(acts):            # acts: list of (start, finish)
    kept, last = [], float('-inf')
    for s, f in sorted(acts, key=lambda a: a[1]):
        if s >= last:                       # starts at or after the last finish
            kept.append((s, f)); last = f
    return kept

def fractional_knapsack(items, W):        # items: list of (weight, value)
    total = 0.0
    for w, v in sorted(items, key=lambda x: x[1] / x[0], reverse=True):
        take = min(w, W); total += v * take / w; W -= take
        if W == 0: break
    return total

def huffman(freq):                         # freq: dict letter -> count, 2+ letters
    tie = count()
    heap = [(f, next(tie), ch) for ch, f in freq.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        fx, _, x = heapq.heappop(heap)        # the two rarest
        fy, _, y = heapq.heappop(heap)
        heapq.heappush(heap, (fx + fy, next(tie), (x, y)))
    codes = {}
    def walk(node, code):
        if isinstance(node, tuple):
            walk(node[0], code + '0'); walk(node[1], code + '1')
        else:
            codes[node] = code
    walk(heap[0][2], '')
    return codes

def min_coins(coins, amount):              # the DP for when greedy is not safe
    C = [0] + [float('inf')] * amount
    for a in range(1, amount + 1):
        C[a] = 1 + min((C[a - c] for c in coins if c <= a), default=float('inf'))
    return C[amount]

Where it sits in the field

Huffman codes are part of real formats you use daily. DEFLATE, the method inside zip, gzip and PNG, codes its data with Huffman trees (RFC 1951). Baseline JPEG uses Huffman tables for its coefficients. HTTP/2 header compression uses a fixed Huffman code (RFC 7541).

Keep going

The takeaway. Greedy is exact only with a proof. Write the swap that puts the greedy choice into an optimal answer. If you cannot, look for the small counterexample, and reach for dynamic programming.
A problem has optimal substructure and overlapping subproblems, but no greedy-choice property. What should you use?

Now press Present or Teach and explain from memory. Say why earliest finish is safe, with the swap. Say why the 0/1 bag gets $160 by greedy but $220 at best. Say what Huffman merges and why the cost is the sum of the merges. Then go back to the hall and run each rule again. This time say which chapter explains each result.

Credit and source

This lesson re-teaches Chapter 16, Greedy Algorithms, of Introduction to Algorithms (third edition) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). Huffman codes are due to David A. Huffman (1952). The text, toys and devices here are our own.

CLRS Chapter 16: Greedy Algorithms
Introduction to Algorithms (MIT Press) · Back to Gleams