3.7.4 · D3Algorithm Paradigms

Worked examples — Greedy problems — activity selection, fractional knapsack, Huffman coding (full algorithm)

2,497 words11 min readBack to topic

This page hammers the three greedy algorithms from the parent topic against every kind of input they can meet: nice inputs, ties, zero/degenerate inputs, and the traps where greedy breaks. Read the matrix first, then each worked example tells you which cell it covers.


The scenario matrix

# Topic Case class What could go wrong Example
C1 Activity Selection Ties in finish time which of two equal-finishers do we take? Ex 1
C2 Activity Selection Touching intervals (start == last finish) is "" or "" correct? Ex 2
C3 Activity Selection Degenerate: 0 or 1 activity does the loop still work? Ex 3
C4 Fractional Knapsack Everything fits (no fraction needed) greedy must not "over-cut" Ex 4
C5 Fractional Knapsack Density tie + real-world words tie-breaking is irrelevant, prove it Ex 5
C6 Fractional Knapsack 0/1 twist — indivisible items greedy density fails; DP wins Ex 6
C7 Fractional Knapsack Zero capacity / zero-weight item division by zero, empty bag Ex 7
C8 Huffman All frequencies equal tree becomes balanced Ex 8
C9 Huffman Merge ties / heap order exam twist: recompute cost Ex 9
C10 Huffman Single symbol (degenerate) codeword length must be 1, not 0 Ex 10

Part A — Activity Selection


Part B — Fractional Knapsack


Part C — Huffman Coding

The next examples use a code-tree picture; the merge order is the whole story.

Figure — Greedy problems — activity selection, fractional knapsack, Huffman coding (full algorithm)

Recall Which cell did each example fix?

Ties in finish time — harmless? ::: Yes — both equal finishers leave the same future window (Ex 1). Do touching intervals overlap under start >= last? ::: No — boundary contact is allowed (Ex 2). Does density-greedy solve 0/1 knapsack? ::: No — Ex 6 gives 160 vs optimal 220; use DP. Huffman with all-equal frequencies gives what tree? ::: A balanced fixed-length tree (Ex 8). Codeword length for a single-symbol alphabet? ::: 1 (never 0), by special case (Ex 10).

Related tools used above: Priority Queue / Binary Heap (Huffman merges), Sorting Algorithms (finish-time / density sort), Exchange Argument (why each greedy pick is safe), Dynamic Programming (the 0/1 fallback), Minimum Spanning Tree (Kruskal/Prim) (another exchange-argument greedy).