Dynamic Programming
The most powerful algorithmic technique in computer science. Transforms exponential brute-force into elegant polynomial solutions.
Fibonacci(50) — 1 quadrillion calls vs 49 calls
The insight: fib(3) appears in the recursion tree dozens of times. Each time, we recompute it from scratch. DP says: compute it once, store it, look it up instantly.
The Two Necessary Conditions
Both must hold for DP to apply. Learn to test for them instantly.
The same smaller problem appears multiple times when solving the larger problem. fib(3) in fib(10) is computed over and over.
The optimal solution to the large problem is built from optimal solutions to its subproblems. Shortest A→C = shortest(A→B) + shortest(B→C).
The 3-Step DP Framework
The thinking process every DP expert uses. Internalize it.
What does dp[i] (or dp[i][j]) represent? Be precise. Vague state = wrong recurrence.
dp[i] = "max profit robbing houses 0..i"How does dp[i] depend on smaller subproblems? What choices exist at each step?
dp[i] = max(dp[i-1], dp[i-2] + nums[i])What are the smallest valid states? These are the seeds your recurrence grows from.
dp[0] = nums[0], dp[1] = max(nums[0], nums[1])4 DP Variants — Know Them All
Every DP problem fits one of these categories.
dp[i] depends on dp[i-1], dp[i-2]. Single array, small lookback.
dp[i] considers ALL previous states — not just adjacent ones.
dp[i][j] has two dimensions: two strings, two sequences, or a grid.
dp[i][j] = answer for subarray [i..j]. Try every split point k.
Pattern Recognition
30-second diagnosis: is this DP?