The Greedy Paradigm & Greedy vs DP
Greedy-choice property, optimal substructure, exchange arguments and matroid theory, and identifying when greedy fails where DP succeeds.
Greedy algorithms construct optimal solutions through a sequence of irrevocable local choices, bypassing exhaustive search and subproblem tabulation. Guided by the Greedy-Choice Property and validated through formal exchange arguments, greedy strategies deliver high-speed solutions for interval scheduling, minimum spanning trees, and fractional resource allocation.
1. Executive Summary & Learning Objectives
#The Greedy Paradigm builds candidate solutions incrementally by selecting the locally optimal choice at each step without backtracking or exploring alternative branches. Pioneered formally through Jack Edmonds' matroid theory (1971), greedy correctness requires establishing two mathematical conditions: the Greedy-Choice Property and Optimal Substructure.
By the end of this chapter, you will be able to:
- Formulate the Greedy-Choice Property and Optimal Substructure with mathematical rigor.
- Execute the Exchange Argument to prove by induction that a greedy sequence matches or exceeds any hypothetical optimal solution.
- Implement and trace Interval Scheduling (Activity Selection) and Fractional Knapsack algorithms in time.
- Identify greedy failure modes through counterexamples (non-canonical coin systems, 0/1 Knapsack) that mandate Dynamic Programming.
- Evaluate trade-offs between greedy heuristics ( speed, memory) and dynamic programming ( optimality guarantees).
2. The Greedy Paradigm & Theoretical Foundations
#A Greedy Algorithm constructs a candidate solution incrementally through a sequence of locally optimal choices without reconsidering earlier choices or evaluating downstream branches:
Structural Characteristics
#- Irrevocability: Once a choice is made, it is permanent. The algorithm never backtracks to reconsider alternatives.
- Top-Down Reduction: Subproblem reduction occurs immediately after each greedy choice is made.
The Two Mandatory Mathematical Conditions
#| Condition | Formal Requirement | Analytical Significance |
|---|---|---|
| 1. Greedy-Choice Property | A globally optimal solution can be assembled by making locally optimal (greedy) choices without consulting future subproblems. | Eliminates the need to evaluate multiple branching paths. |
| 2. Optimal Substructure | An optimal solution to the instance contains within it optimal solutions to resulting subproblems: . | Ensures subproblems can be solved independently. |
3. Mathematical Proof: The Exchange Argument
#The standard rigorous method for proving greedy correctness is the Exchange Argument: we establish that any hypothetical optimal solution can be transformed into the greedy solution step-by-step without degrading objective value.
Theorem: Interval Scheduling (Activity Selection)
#Given intervals with start times and finish times , selecting activities in ascending order of finish time produces a schedule of maximum possible cardinality.
Inductive Proof via Exchange:
Let be the set of activities selected by the greedy algorithm, ordered by finish time: .
Let be an arbitrary optimal solution, ordered by finish time: . We must prove .
- Base Case (): By construction, greedy selects such that .
Therefore, .
Construct modified solution . Since , activity does not conflict with . Thus is valid and . - Inductive Step: Assume there exists an optimal solution whose first activities match : .
Because greedy selects as the activity with earliest finish time starting after , we have .
Substituting in place of leaves activities valid because . - Conclusion: By induction, the entire set can replace the first elements of an optimal solution. If , there would exist an activity compatible with , contradicting greedy termination. Hence, , and is globally optimal.
4. Step-by-Step Worked Dry Run: Activity Selection
#Consider activities sorted by ascending finish times:
- , , , , , , ,
| Order by | Activity | Interval | Last Finish Time | Conflict Test () | Selection Decision | Active Set |
|---|---|---|---|---|---|---|
| 1 | (Init) | SELECT | ||||
| 2 | REJECT (Overlap) | |||||
| 3 | REJECT (Overlap) | |||||
| 4 | SELECT | |||||
| 5 | REJECT (Overlap) | |||||
| 6 | REJECT (Overlap) | |||||
| 7 | REJECT (Overlap) | |||||
| 8 | SELECT |
Result: Maximum compatible set cardinality is : . Runtime: for initial sorting.
export interface Interval {
id: number;
start: number;
finish: number;
}
export function selectActivities(activities: Interval[]): Interval[] {
// Sort by ascending finish times - O(n log n)
const sorted = [...activities].sort((a, b) => a.finish - b.finish);
const selected: Interval[] = [];
let lastFinish = -Infinity;
for (const act of sorted) {
if (act.start >= lastFinish) {
selected.push(act);
lastFinish = act.finish;
}
}
return selected;
}5. Step-by-Step Worked Dry Run: Fractional Knapsack
#Given knapsack capacity and 4 items:
- Item 1: v_1 = 60, w_1 = 10 \implies \rho_1 = 6.0\text{ </span>/kg}$
- Item 2: v_2 = 100, w_2 = 20 \implies \rho_2 = 5.0\text{ </span>/kg}$
- Item 3: v_3 = 120, w_3 = 30 \implies \rho_3 = 4.0\text{ </span>/kg}$
- Item 4: v_4 = 50, w_4 = 25 \implies \rho_4 = 2.0\text{ </span>/kg}$
| Density Rank | Item | Value () | Weight () | Density | Capacity Left | Fraction Taken | Value Accrued | Cumulative Profit |
|---|---|---|---|---|---|---|---|---|
| 1 | Item 1 | </span>6010\text{ kg}<span class="katex"> | (Full) | </span>60<span class="katex"> | ||||
| 2 | Item 2 | </span>10020\text{ kg}<span class="katex"> | (Full) | </span>100<span class="katex"> | ||||
| 3 | Item 3 | </span>12030\text{ kg}<span class="katex"> | \frac{2}{3} \times </span>120 = <span class="katex"> | </span>240$ | ||||
| 4 | Item 4 | </span>5025\text{ kg}<span class="katex"> | (Skipped) | </span>0<span class="katex"> |
Conclusion: Greedily sorting by value density yields maximum possible profit of </span>240O(n \log n)$ time.
6. Greedy vs. Dynamic Programming
#Whenever the Greedy-Choice Property fails, greedy algorithms yield suboptimal or incorrect results.
The Coin Change Counterexample
#Given coin denominations and target value :
| Coin System | Target | Greedy Strategy (Largest Coin First) | Optimal Strategy (Dynamic Programming) | Greedy Status |
|---|---|---|---|---|
| US Canonical | (2 coins) | (2 coins) | OPTIMAL | |
| Non-Canonical | (3 coins) | (2 coins) | FAILED | |
| Arbitrary | (5 coins) | (2 coins) | FAILED |
Matroid Theory Insight (Pearson, 1994): A coin system is canonical if and only if the change-making problem satisfies Pearson's algebraic test. Arbitrary coin systems lack the greedy-choice property and require Dynamic Programming.
7. Master Comparison: Greedy vs. Dynamic Programming
#| Dimension | Greedy Paradigm | Dynamic Programming (DP) |
|---|---|---|
| Decision Policy | Irrevocable local choice at each step; never backtracks | Evaluates all valid subproblem transitions before committing |
| Subproblem Structure | Solves independent subproblems sequentially | Solves overlapping subproblems via memoization or tabulation |
| Proof Burden | High (Exchange argument or matroid isomorphism required) | Moderate (Verification of optimal substructure recurrence) |
| Time Complexity | Typically (sorting) or | Polynomial or pseudo-polynomial |
| Space Complexity | Typically auxiliary memory | Requires memory for state tables () |
| Failure Mode | Produces suboptimal solutions if greedy-choice property fails | Guaranteed globally optimal provided recurrence is sound |
8. Common Traps, Edge Cases & Implementation Pitfalls
#- Applying Greedy to 0/1 Knapsack:
- Greedily sorting by value density works for fractional knapsack, but fails catastrophically for 0/1 knapsack where items cannot be divided. 0/1 knapsack requires pseudo-polynomial DP.
- Sorting by Start Time in Interval Scheduling:
- Selecting activities by earliest start time fails (e.g., an activity starting at spanning until would block multiple shorter activities). Always sort by earliest finish time.
- Floating-Point Density Inaccuracy:
- In fractional knapsack, comparing density using division
v1 / w1 < v2 / w2induces IEEE-754 precision errors. Compare using cross-multiplication:v1 * w2 < v2 * w1.
- In fractional knapsack, comparing density using division
9. Real-World Applications & Practice Problems
#Production Systems
#- Huffman Coding (Data Compression): Greedily merges the two least frequent character trees to construct optimal prefix codes (gzip, JPEG).
- Network Routing Protocols (OSPF / Prim's MST): Dijkstra and Prim greedily extend shortest routes and minimum spanning connections.
- CPU Task Schedulers (Earliest Deadline First / EDF): Schedules real-time processes greedily by closest deadline to guarantee optimal schedulability on uniprocessors.
Practice Problems
#- Non-overlapping Intervals (LeetCode 435) — Activity selection greedy finish-time ordering.
- Jump Game (LeetCode 55) — Greedy reachability tracking in time.
- Gas Station (LeetCode 134) — Greedy circular tour validation in single pass.
10. References & Academic Attribution
#- Edmonds, J. (1971). Matroids and the greedy algorithm. Mathematical Programming, 1(1), 127–136.
- Pearson, D. (1994). A polynomial-time algorithm for the change-making problem. Operations Research Letters, 33(3), 231–234.
- Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms (4th ed.), Chapter 15 (Greedy Algorithms). MIT Press.
- Kleinberg, J., & Tardos, É. (2006). Algorithm Design, Chapter 4 (Greedy Algorithms). Pearson.