"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 where the greedy choice forecloses the best answer, you need DP, which considers all choices and caches. Finding even one counterexample to greedy is proof that you need DP.
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
Why not just always use DP, since it's safe? Because greedy, when valid, is dramatically cheaper — fractional knapsack is O(n log n) for the sort versus 0/1's O(n × capacity) table, and greedy uses O(1) extra space versus DP's table. When greedy is provably correct, paying for DP is waste. So the judgment is real and bidirectional: don't trust an unproven greedy (last lesson), but don't reach for a heavy DP when a proven greedy would do. The skill is matching the paradigm to the problem's actual structure.