The pattern: dynamic programming
Master 1D state transitions, Kadane's algorithm, unbounded & 0/1 knapsack, multi-state choices, grid paths, and 2D string matching.
Dynamic Programming (DP) is an optimization technique that solves complex problems by breaking them down into overlapping subproblems and optimal substructure. Rather than recomputing solutions repeatedly, DP computes each subproblem once, saves the result, and combines them to solve the overall problem.
01The core framework
Every dynamic programming problem boils down to five fundamental questions:
- State representation: What does
dp[i](ordp[i][j]) represent in plain words? - Base cases: What are the smallest non-decomposable subproblems (e.g.
dp[0] = 0or empty string)? - Transition relation (recurrence): How does
dp[i]derive its value from previously solved subproblems? - Order of computation: In what direction must the table or rolling variables be filled so dependencies are always ready?
- Location of final answer: Where does the overall solution reside (e.g.
dp[n],max(dp),dp[m][n])?
021. 1D Transitions & rolling variables
When dp[i] only depends on a constant number of previous values (like Fibonacci, Tribonacci, or Climbing Stairs), we never need a full array of size n.
- Keep 2 or 3 rolling variables to achieve
O(1)space complexity while retainingO(n)time.
032. Kadane's algorithm & state resetting
For contiguous subarray optimization (Maximum Subarray, Maximum Product Subarray):
- At index
i, we make a local decision: extend the previous running subarray or restart a fresh subarray atnums[i]. - With products, negative numbers invert signs, so we simultaneously track both maximum and minimum running products (
hiandlo).
043. Take / Skip state machines
Problems with constraints on adjacent selections (like House Robber):
- Maintain explicit states representing decisions:
take(robbed current) vsskip(did not rob current). robHere = skip + money; skip = max(prevSkip, prevTake); take = robHere.
054. Knapsack patterns
- Unbounded knapsack (Coin Change): Each item can be reused unlimited times. Loop through states forwards:
dp[a] = min(dp[a], dp[a - c] + 1). - 0/1 Knapsack (Partition Equal Subset Sum, Ones and Zeroes): Each item can be chosen at most once. Loop budgets backwards to ensure each item is incorporated only once per state.
065. Grid DP & string alignment
- Grid paths (Triangle, Falling Path Sum): Transition from previous row cells:
cur[c] = val + min(parents). - 2D String alignment (Edit Distance): If characters match, take diagonal free
dp[i-1][j-1]. If they differ, pay 1 +min(replace, delete, insert).