"Greedy and dynamic programming are rivals for the same throne. The knapsack problem shows the whole drama: change one rule — can you split an item or not? — and the crown passes from greedy to DP."
The Core Decision
Greedy and DP both build solutions from subproblems, so for any optimization problem you'll often face a fork: can I get away with the fast greedy choice, or must I pay for DP's exhaustive search? The deciding question is whether the greedy-choice property holds — does committing to the locally-best option always keep a globally-optimal solution reachable? If yes, greedy wins (faster, simpler, no table). If a counterexample exists, that greedy rule is invalid. DP may be the right replacement when reusable state and a valid recurrence exist, but other algorithms remain possible. One counterexample disproves that greedy rule; it does not prove DP is the only possible replacement.
The Knapsack: One Rule Flips Everything
The cleanest illustration in all of algorithms. You have a knapsack with a weight limit and items with weights and values:
- Fractional knapsack (you may take a fraction of an item): greedy is optimal. Sort by value-per-weight, take the best ratio first, and when the next item doesn't fully fit, take just the fraction that does. Provably optimal — the ratio ordering can't be beaten when you can split.
- 0/1 knapsack (each item is all-or-nothing): greedy fails, you need DP. Because you can't split, taking the best-ratio item can crowd out a better combination. The fix is the 2D DP from the last track — dp[item][capacity].
Same items, same weights, same goal. The single rule 'can you split?' decides whether the right tool is a one-line greedy sort or a full DP table. That's the paradigm-choice skill in miniature: a tiny change in the problem's constraints can flip which strategy is correct.
The Cost of the Choice
Fractional knapsack takes O(n log n) for sorting, and the sort may use additional space. The O(n·C) integer-capacity DP for 0/1 knapsack is pseudopolynomial in the numeric capacity C. For large C, meet-in-the-middle, approximation, or other methods may fit better.