Notes
All notes

Greedy Algorithms (DSA #25)

You are scheduling as many meetings as possible in one room. The obvious greedy rule — take the shortest meeting first — sounds reasonable and is wrong. Taking the one that ends earliest is right. Both are greedy; only one is correct. That is the trap and the power of greedy algorithms: when a local rule is provably optimal, the algorithm becomes short and fast; when it is not, the algorithm is subtly wrong in ways that pass small tests.

This chapter covers the conditions under which greedy works, the exchange argument that proves it, and the standard problems — including one where greedy famously fails.

What makes a greedy algorithm

A greedy algorithm builds a solution piece by piece, always choosing the option that looks best right now, and never revisiting a choice. It is correct only when the problem has two properties:

The hard part is never the code — greedy code is usually a few lines — but proving the rule is right. Without a proof, you have a heuristic that may fail on inputs you have not tried.

The exchange argument

The standard proof technique. Suppose the greedy choice is \(g\) and an optimal solution uses some other first choice \(o\). Show you can transform the optimal solution to use \(g\) without making it worse. If you can, then there exists an optimal solution starting with \(g\), and you can recurse.

For interval scheduling: let \(g\) be the interval with the earliest finish. In any optimal set whose first interval \(o\) finishes later, replace \(o\) with \(g\). Since \(g\) finishes no later, it conflicts with no more intervals, so the rest of the set remains valid — and the size is unchanged. Therefore some optimal solution starts with \(g\).

Interval scheduling

Given intervals with start and finish times, choose the maximum number of non-overlapping intervals.

Greedy rule: sort by finish time, take each interval that starts after the last chosen one ends.

def max_intervals(intervals):
    intervals.sort(key=lambda x: x[1])        # by finish time
    count, last_end = 0, float("-inf")
    chosen = []
    for start, end in intervals:
        if start >= last_end:                 # no overlap with last chosen
            chosen.append((start, end))
            last_end = end
            count += 1
    return count, chosen

Rules that fail: choosing the shortest interval, or the one that starts earliest. Both can block more intervals than they enable. Only earliest-finish has the exchange argument.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum height=0.42cm, font=\scriptsize},
  a/.style={->, thick, black!40}]
  \draw[a] (0,0) -- (7.2,0) node[below, font=\small] {time};
  \fill[green!30] (0.2,0.2) rectangle (1.4,0.5);   \node[font=\scriptsize] at (0.8,0.35) {chosen};
  \fill[gray!20] (0.6,0.8) rectangle (2.6,1.1);     \node[font=\scriptsize] at (1.6,0.95) {skip};
  \fill[green!30] (1.6,1.4) rectangle (3.0,1.7);    \node[font=\scriptsize] at (2.3,1.55) {chosen};
  \fill[gray!20] (2.2,2.0) rectangle (4.0,2.3);     \node[font=\scriptsize] at (3.1,2.15) {skip};
  \fill[green!30] (3.2,2.6) rectangle (5.0,2.9);    \node[font=\scriptsize] at (4.1,2.75) {chosen};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.6,-0.5) {pick earliest finish, skip overlaps, repeat};
\end{tikzpicture}

Fractional knapsack

Items have weight and value; the knapsack holds a weight limit; you may take fractions. Greedy is optimal: sort by value-to-weight ratio and take as much as fits.

def fractional_knapsack(items, capacity):
    items.sort(key=lambda it: it[1] / it[0], reverse=True)   # value/weight
    total = 0.0
    for weight, value in items:
        if capacity >= weight:
            total += value
            capacity -= weight
        else:
            total += value * capacity / weight   # take the fraction
            break
    return total

This is where greedy succeeds and the 0/1 knapsack fails: with indivisible items, the ratio rule can be wrong. That problem needs dynamic programming (Chapter 26) — a canonical contrast.

# 0/1 knapsack: greedy on ratio is WRONG
# items (weight, value): (10, 60), (20, 100), (30, 120) ; capacity 50
# ratio greedy: 60 (10), 100 (20) -> value 160, no room; optimum is 220 (20+30)

Huffman coding

Build a prefix-free code that minimises expected message length by repeatedly merging the two least frequent symbols. A min-heap (Chapter 11) drives it.

import heapq
def huffman(freq):
    heap = [[w, [sym, ""]] for sym, w in freq.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        lo = heapq.heappop(heap)
        hi = heapq.heappop(heap)
        for pair in lo[1:]: pair[1] = "0" + pair[1]
        for pair in hi[1:]: pair[1] = "1" + pair[1]
        heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
    return sorted(heap[0][1:], key=lambda p: (len(p[1]), p[1]))

Huffman is greedy and optimal: merging the two rarest symbols is exactly the move the exchange argument defends, and it underlies gzip, PNG, and MP3 compression.

Other greedy wins

Greedy vs dynamic programming

Greedy Dynamic programming
Choice commit, never revisit consider all, reuse results
Proof exchange argument recurrence + optimal substructure
Speed usually fast, low memory slower, often table memory
Example interval scheduling 0/1 knapsack

Rule of thumb: try greedy, but prove it or test it against brute force on small cases. If a counterexample appears, switch to dynamic programming.

Pitfalls

QQuestionSelf-check

What two properties must hold for greedy to be correct, and what is the exchange argument? Why does greedy fail for 0/1 knapsack?

ASolution

Greedy choice property and optimal substructure. The exchange argument shows any optimal solution can be transformed to start with the greedy choice without becoming worse, so the greedy choice is safe. For 0/1 knapsack, taking the best ratio first can consume capacity that would have been better spent on a combination of lower-ratio items, so no local rule is optimal — you need dynamic programming.

Next: Dynamic Programming (DSA #26) — trading memory for the exponential recomputation of overlapping subproblems.