ADVANCEDFrequently Tested 4 min read 22 views
Dynamic Programming Masterclass: 0/1 Knapsack, LCS & Matrix Chain Multiplication
Optimal substructure & overlapping subproblems, exact DP recurrences, time/space complexities, and pseudo-polynomial complexity of 0/1 Knapsack.
1. Greedy vs Dynamic Programming Decision Matrix
| Classic Problem | Greedy Works? | Optimal Paradigm | Time Complexity | Space |
|---|---|---|---|---|
| Fractional Knapsack | Yes (Sort by ) | Greedy | ||
| 0/1 Knapsack | No! | Dynamic Programming | (Pseudo-polynomial) | |
| Activity Selection | Yes (Earliest finish time) | Greedy | ||
| Huffman Optimal Prefix Code | Yes (Min-Heap merge 2 smallest) | Greedy | ||
| Matrix Chain Multiplication | No! | Dynamic Programming | ||
| Longest Common Subsequence | No! | Dynamic Programming | ||
| All-Pairs Shortest Path | — | Floyd-Warshall DP |
2. Matrix Chain Multiplication Worked Insight
To multiply , say :
- costs scalar multiplications.
- costs — a 10× penalty for wrong parenthesization!
Common Exam Mistake
Why is for 0/1 Knapsack NOT polynomial time? Because the input size in bits to represent capacity is , so . Thus is exponential in bit-length (pseudo-polynomial)!
Key Formulas Summary
Longest Common Subsequence (LCS) Recurrence
Note: Time: Theta(mn), Space: O(min(m, n)) with rolling 2-row optimization
Matrix Chain Multiplication (MCM)
Note: Time: Theta(n^3), Space: Theta(n^2) for n matrices
#Algorithms#Dynamic Programming#Knapsack#LCS#Matrix Chain#Floyd-Warshall
Practice Questions on This Chapter (3)
Q1GATE CS AlgorithmsMCQMEDIUM
+2M • -0.67
What is the length of the Longest Common Subsequence (LCS) of strings and ?
⚡ Click an option above to verify instantly
Q2GATE CS 2016NATMEDIUM
+2M • 0 Neg
What is the minimum number of scalar multiplications required to multiply four matrices ?
Q3GATE CS 2019NATEASY
+2M • 0 Neg
What is the length of the Longest Common Subsequence (LCS) between strings X = "AGGTAB" and Y = "GXTXAYB"?