Greedy Algorithms
Algorithms · Advanced Placement
Greedy Algorithms: the big picture
A greedy algorithm makes the choice that looks best at each step and never reconsiders, which is far cheaper than dynamic programming but correct only when the problem has the greedy choice property: some optimal solution contains the locally optimal first choice. Proving that property is the whole work of designing a greedy algorithm, and the standard technique is an exchange argument showing that any optimal solution can be transformed to contain the greedy choice without becoming worse. Activity selection, choosing the maximum number of non-overlapping intervals, is solved by repeatedly taking the activity that finishes earliest, and the exchange argument is short and convincing. Huffman coding builds an optimal prefix-free code by repeatedly merging the two least frequent symbols, which yields shorter codes for more frequent symbols and is optimal among all prefix codes for a known symbol distribution. The fractional knapsack is greedy on value per unit weight, whereas the 0-1 version is not, which is the standard illustration of where the greedy choice property fails. Matroid theory characterises a class of problems for which greedy algorithms are provably optimal, which includes minimum spanning trees. When greedy fails it often still gives a bounded approximation, which is valuable for NP-hard problems.
The Greedy Choice Property, Exchange Arguments & Activity Selection
A greedy algorithm takes the locally best option and never looks back, which is cheap but correct only when the problem has the greedy choice property — that some optimal solution contains that first choice. Proving it is the actual work, and the standard tool is an exchange argument: take any optimal solution, show you can swap in the greedy choice without making it worse. Activity selection is the cleanest example, and the fractional versus 0-1 knapsack contrast shows exactly where the property fails.
{{illustration:algos-l12-f1}}
{{illustration:algos-l12-f2}}
Key relations
- The greedy choice property. ∃ optimal S: g ∈ S where g is the greedy choice ; T(n) = O(nlog n)
Huffman Coding, Prefix-Free Codes & Compression Limits
Huffman coding builds an optimal prefix-free code by repeatedly merging the two least frequent symbols, which gives frequent symbols short codes and rare ones long codes. The prefix-free property is what makes the result decodable without delimiters: no code is a prefix of another, so the decoder always knows when a symbol ends. Huffman is optimal among prefix codes for a known distribution, but it cannot beat the entropy of the source — that is the information-theoretic floor, and arithmetic coding gets closer to it than Huffman can.
{{illustration:algos-l12-f3}}
{{illustration:algos-l12-f4}}
Key relations
- Entropy and expected code length. H = -∑ᵢ pᵢlog₂pᵢ ; H ≤ L_Huffman < H + 1 ; L = ∑ᵢ pᵢℓᵢ