Greedy Paradigm and Activity Selection
In questa pagina 4
The third paradigm after divide and conquer and Dynamic Programming - Paradigm and Memoizationdynamic programming improves on divide and conquer by storing the solutions of repeated subinstances in a table; Fibonacci shows the gap (F_n - 1 additions recursively, n - 1 with a table), memoization is recursion plus a global table, and optimization problems follow a five-step scheme built on optimal substructure and cut-and-paste.Dynamic Programming - Paradigm and Memoization →. It applies to optimization problems: among the feasible solutions of an instance, find one of minimum or maximum cost.
From dynamic programming to greedy
In a DP algorithm the optimal solution is obtained by composing a sequence of choices, and the information saved to rebuild it (the index for matrix chains, the arrow in the LCS table) is precisely the choices. But each choice is deliberate: it can only be made after solving many subinstances (all the values of , all three LCS subinstances). This caution makes DP widely applicable but has a cost (a table and work per cell).
For some problems the approach can be reversed:
- Greedy choice: make immediately the first choice, the one that locally looks best, without solving any subinstance.
- Clean-up: remove the elements incompatible with the choice. What is left is a single subinstance, the residual subinstance, solved with the same procedure.
Consequences.
- Each instance has one subinstance, so the subinstance space is at most linear and there are no repeated subinstances: memoization is useless.
- The only recursive call is the last instruction after the clean-up: tail recursion, removed with a loop alternating greedy choice and clean-up. The algorithms are iterative, simple and fast, often linear or almost linear, based on one scan of the instance.
- The drawback is that it does not always work. The class of problems solvable this way is small but contains important cases: minimum spanning trees, shortest paths and optimal data compression (Huffman Codescharacter-by-character compression needs an injective variable-length code, which prefix codes guarantee; a prefix code is a binary trie with one leaf per character of cost B(T) = sum of f(c) d_T(c), the optimal trie is full with n-1 internal nodes, Huffman repeatedly merges the two lowest-frequency trees using a priority queue (2n-1 extractions, O(n log n)), and optimality follows from the greedy choice (two rarest characters are deepest sibling leaves, by exchange) and substructure B(T) = B(T') + f(x) + f(y).Huffman Codes →).
The code comes before the analysis. In D&C and DP one studies the substructure and then writes the algorithm; here the code follows directly from the definitions of greedy choice and clean-up, and is easy. The hard work is proving it correct, and equally natural greedy choices may give wrong solutions.
The two properties to prove
Greedy choice property. There is always an optimal solution that contains the greedy choice. It guarantees that the reckless choice does not compromise optimality.
Optimal substructure property. There is an optimal solution that, besides the greedy choice, contains an optimal solution of the residual subinstance.
Typical techniques:
- Greedy choice: start from any optimal solution ; if it does not contain the greedy choice, modify it (exchange, or cut-and-paste) into containing it, without worsening the cost. Then is still optimal.
- Substructure: by contradiction. If the part of left after the greedy choice were not optimal for the residual, replace it with an optimal one (cut-and-paste) obtaining a better solution of the original instance: contradiction.
Theorem (correctness scheme). If a greedy algorithm always makes the greedy choice, cleans up and solves the residual recursively, and the two properties hold, then it returns an optimal solution.
Proof. By induction on the instance size. Base: the empty instance, the empty solution is optimal. Step: assume the algorithm is correct on smaller instances, in particular on the residual, which is strictly smaller. By the two properties there is an optimal made of the greedy choice and an optimal solution of the residual. The algorithm returns the greedy choice plus the solution that the induction hypothesis guarantees optimal for the residual: same cost as , hence optimal.
The inductive reasoning is always the same: only the two properties change from problem to problem. See Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxinghow to set up and prove a greedy exercise (greedy choice, clean-up, algorithm, greedy choice property by exchange, optimal substructure by contradiction, induction) applied to three problems with empty clean-up: CD tracks (fill the first CD, Theta(n)), shortest-first scheduling (sort by duration, SJF holds for every optimum, O(n log n)) and (2,1)-boxing (pair the heaviest with the lightest, Theta(n)).Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxing →.
The counterexample. To show that a greedy strategy is wrong it suffices to give one instance in which the greedy choice excludes every optimum, which is much easier than proving correctness.
The activity selection problem
A shared resource (a classroom) and a set of activities that want to use it. Activity occupies the interval with (start included, finish excluded).
Definition. Two activities and are compatible if their intervals are disjoint, i.e. A subset is mutually compatible if all pairs are. The problem (activity selection) asks for a mutually compatible subset of maximum cardinality.
Since intervals are open on the right, an activity ending and another starting at the same instant are compatible.
Example. , , i.e. , , , , , .
The greedy algorithm
Assume sorted by non-decreasing finish time, ; otherwise sort in . The order is crucial for correctness.
- Greedy choice: the first activity, , the one that finishes first. Intuition: it leaves the resource free for the longest contiguous interval.
- Clean-up: remove the following activities incompatible with , i.e. with , up to the first compatible one , . The residual is the suffix (empty if none is compatible). Residual instances are always suffixes, identified by an index : the main instance is and the empty one .
REC_GREEDY_SEL(s, f, i) {activities sorted by finish}
n <- s.len
if i > n then return {}
G <- {i}
j <- i + 1
while j <= n and s[j] < f[i] do // clean-up: discard incompatible ones
j <- j + 1
return G U REC_GREEDY_SEL(s, f, j)In the while condition j <= n is tested first: the opposite order would read s[n+1]. Call with . The recursion is a tail one and is removed. It suffices to remember the last chosen activity and compare every activity with it:
IT_GREEDY_SEL(s, f)
n <- s.len
A <- {1}
g <- 1 // last greedy choice
for i <- 2 to n do
if s[i] >= f[g] then // compatible with the last choice
A <- A U {i}
g <- i
return Adef it_greedy_sel(s, f): # 1-based indices as in the text; s, f already sorted by finish
A, g = [1], 1
for i in range(2, len(s) + 1):
if s[i - 1] >= f[g - 1]:
A.append(i); g = i
return AComplexity. The scan performs exactly comparisons ( for ) and at most insertions: . Sorting by finish time costs and dominates if the data are unsorted.
Worked example
Same instance, , .
| test | outcome | ||||
|---|---|---|---|---|---|
| 1 | initial choice | chosen | 1 () | ||
| 2 | no | discarded | 1 | ||
| 3 | no | discarded | 1 | ||
| 4 | yes | chosen | 4 () | ||
| 5 | no | discarded | 4 | ||
| 6 | yes | chosen | 6 |
The clean-up after choosing removes and (they start before ): the first activity of the residual subinstance is , since . The result has 3 activities, the maximum ( is also optimal).
Why the clean-up may be limited. It removes only the incompatible activities that immediately follow , not all those incompatible with . This does not compromise correctness: an incompatible activity not removed will be incompatible with some later greedy choice and discarded then. Example with : after choosing the clean-up removes () and stops at ; the residual still contains , incompatible with , but is chosen and discards (); the result is , optimal. The effect is a single linear scan.
Correctness
Notation: (suffix), (with if none exists), the maximum cardinality of a mutually compatible subset of , .
Greedy choice property. has an optimal solution containing .
Proof (exchange). Let be optimal for . If put . Otherwise let be the activity of of minimum index; since , . Put We must show is feasible, i.e. is compatible with every . Since and are together in they are compatible: or . The second is impossible: it would give (the last inequality because and the order is by finish). So and by the order so starts after finishes: compatible.
Optimal substructure property. .
Proof. () By the greedy choice property there is an optimal of with . Every is compatible with and has , so (the other alternative would give ). An activity with has , hence by minimality: and is compatible, so .
() Let be optimal for , . Not every solution of will do: it may contain activities incompatible with (like above). By the greedy choice property applied to , choose an optimal containing . Every other is compatible with and has , so ; also has by definition of . So is feasible and .
Theorem. returns a feasible solution of of cardinality .
Proof. Induction on . Base: , returns , . Step: the algorithm returns with (the clean-up loop computes exactly ). By induction is feasible in with elements; its first element is and the others start after , so all start after and is feasible, with cardinality .
The iterative algorithm computes the same indices (it compares each activity with the last chosen one and, by transitivity of the increasing finish times, with all earlier ones).
Greedy choices that do not work
Other choices look reasonable but are wrong; one counterexample each suffices.
| Strategy | Instance | What happens |
|---|---|---|
| shortest duration | picks (duration 2), incompatible with both others: 1 activity, while has 2 | |
| earliest start | picks and blocks everything: 1 against 2 | |
| fewest incompatibilities | 11 activities: , , , , , , , , , , | has 2 incompatibilities (with and ), all others at least 3: the choice falls on and at most 3 activities result; the optimum has 4 |
The symmetric rule works: sorting by non-increasing start and choosing the activity that starts last, with the same kind of clean-up, mirrors the proof above.
Beware of weights. If each activity has a weight and the sum of weights is maximized, the earliest-finish greedy is not enough ( with weight 100 against with weight 1 each): dynamic programming is needed.
Typical exam questions
- For , , what is the index of the first activity of the residual subinstance after the first greedy choice and clean-up? Answer: greedy choice ; () and () are removed, has : index 4.
- Which two properties ensure the correctness of a greedy algorithm and how are they proved? Answer: greedy choice (an optimum containing it exists: exchange from an optimum without worsening the cost) and optimal substructure (contradiction with cut-and-paste); correctness follows by induction on the size.
- Why is sorting by finish time crucial? Give a counterexample for "shortest duration". Answer: the exchange uses , which needs the finish order; counterexample .
Versione ripasso
- From DP to greedy: in DP each choice is deliberate (many subinstances solved first); in greedy the locally best choice is made at once, then the instance is cleaned up (clean-up) and a single residual subinstance remains.
- Consequences: linear subinstance space, no repeated subinstances (memoization useless); tail recursion becomes a loop; simple, fast, often linear algorithms. It does not always work: good cases are minimum spanning trees, shortest paths, Huffman Codescharacter-by-character compression needs an injective variable-length code, which prefix codes guarantee; a prefix code is a binary trie with one leaf per character of cost B(T) = sum of f(c) d_T(c), the optimal trie is full with n-1 internal nodes, Huffman repeatedly merges the two lowest-frequency trees using a priority queue (2n-1 extractions, O(n log n)), and optimality follows from the greedy choice (two rarest characters are deepest sibling leaves, by exchange) and substructure B(T) = B(T') + f(x) + f(y).Huffman Codes →.
- Code first, proof later. Correctness needs two properties: (1) greedy choice, an optimum contains the greedy choice (start from an optimum , exchange to without worsening cost); (2) optimal substructure, an optimum contains the greedy choice plus an optimum of the residual (contradiction and cut-and-paste).
- Correctness scheme: induction on size; base the empty instance; step: by (1) and (2) an optimum made of greedy choice plus an optimum of the residual exists, the algorithm returns greedy choice plus the residual solution, optimal by induction, hence of the same cost. To refute a strategy, a counterexample suffices.
- Activity selection: ; compatible if or (touching endpoints are fine). Find a mutually compatible subset of maximum cardinality. Sort by finish time ().
- Choice and clean-up: greedy choice (earliest finish); clean-up removes the next ones with up to ; residual is the suffix . The clean-up is limited: an incompatible one not removed (e.g. in ) is discarded by a later choice.
- Iterative code:
A <- {1}; g <- 1; for i <- 2 to n: if s[i] >= f[g] then A <- A U {i}; g <- i. Exactly comparisons, . InREC_GREEDY_SELthewhiletestsj <= nfirst. - Example: , : discarded (), chosen (), discarded (), chosen (): , optimal. The residual after starts at .
- Greedy choice (proof): optimal, of minimum index, . For any other : the alternative would give , impossible, so and : is feasible with the same cardinality.
- Substructure (proof): . : an optimum has , since implies hence . : take an optimum of containing (not any one, it might have activities incompatible with ); the others start after , so is feasible.
- Wrong strategies (counterexamples): shortest duration (: 1 against 2), earliest start (), fewest incompatibilities (11 activities: optimum 4, greedy gets 3). The symmetric version (non-increasing start order) is correct. With weights greedy is not enough: use DP.
- Typical mistakes: not sorting by finish; using (excluding compatibility at a point); taking any optimum of the residual without imposing its greedy choice; skipping the feasibility check of the exchange; miscounting comparisons (, not ).