What are Greedy Algorithms and Dynamic Programming?
Solution and explanation
Greedy algorithms
A greedy algorithm builds a solution step by step, always taking the choice that looks best right now, and never revisits it. It is fast and simple, but it only gives the optimal answer when the problem has the greedy-choice property (a locally best choice is part of some globally best solution) and optimal substructure.
Example where greedy works: making change with Indian coins (1, 2, 5, 10, 20…): always take the largest coin that fits. Example where greedy fails: coins {1, 3, 4} for amount 6 – greedy picks 4+1+1 (3 coins) but 3+3 (2 coins) is optimal. That needs DP.
Dynamic programming (DP)
DP solves problems that have:
- Optimal substructure – the best answer is built from best answers to subproblems.
- Overlapping subproblems – the same subproblems repeat, so we store results instead of recomputing them.
Two styles:
- Top-down (memoisation): write the recursion and cache results in a map/array.
- Bottom-up (tabulation): fill a table from the smallest subproblems upward, often reducible to O(1) extra space.
// Fibonacci: plain recursion O(2^n) → DP O(n)
static long fibMemo(int n, long[] memo) {
if (n <= 1) return n;
if (memo[n] != 0) return memo[n];
return memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
}
static long fibTable(int n) {
if (n <= 1) return n;
long prev = 0, cur = 1;
for (int i = 2; i <= n; i++) { long next = prev + cur; prev = cur; cur = next; }
return cur;
}
A recipe for DP problems
- Define the state: what does dp[i] (or dp[i][j]) mean in words?
- Write the transition: how dp[i] depends on smaller states.
- Set base cases.
- Choose the order of computation and where the answer is.
- Optimise space if only the previous row/values are needed.
Greedy vs DP
- Greedy: one choice per step, no backtracking, usually O(n log n) after sorting.
- DP: considers all relevant choices via stored subproblems, usually O(n²) or O(n·W).
- Prove greedy correct (exchange argument) or find a counterexample; if it fails, try DP.
Real-world use
- Greedy: Huffman compression, scheduling meetings, Dijkstra, minimum spanning trees.
- DP: diff tools (longest common subsequence), spell check (edit distance), route planning, inventory and budget allocation (knapsack).
