1. Break down into overlapping subproblems 2. Cache results to avoid solving same subproblems What is Dynamic Programming “Dynamic Programming was basically a phrase made up to confuse the government about what RAND was doing.” - Richard Bellman, ‘father’ of dynamic programming
Sounds easy in theory, but way harder in practice! Like all other problems, the key is to recognize common patterns Why is Dynamic Programming so difficult?
Sounds easy in theory, but way harder in practice! Like all other problems, the key is to recognize common patterns Continuous practice is critical - you’re probably not going to master dynamic programming in 2 weeks. Why is Dynamic Programming so difficult?
Fibonacci What if we built up the fibonacci sequence first? 0 1 1 2 3 5 8 int dp[] = new int[n + 1]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2]; return dp[n];
Fibonacci What if we built up the fibonacci sequence first? 0 1 1 2 3 5 8 int dp[] = new int[n + 1]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2]; return dp[n]; Run time: ??
Fibonacci What if we built up the fibonacci sequence first? 0 1 1 2 3 5 8 int dp[] = new int[n + 1]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2]; return dp[n]; Run time: n