Skip to content

1-D Dynamic Programming

1-D Dynamic Programming in under a minute

Dynamic programming is recursion that remembers. If a problem asks for the best value or the number of ways, and the same sub-question appears many times, you solve each sub-question once and build up. The 1-D kind needs only a single array (or a few variables).

  • The question asks for a maximum, minimum, or count of ways, not the actual choices.
  • At each step you make a choice (take or skip, 1 step or 2, which coin).
  • The brute force is exponential recursion where the same arguments repeat.
  • The answer at position i depends on earlier positions (i-1, i-2, i-coin).
  • Greedy fails on a small counterexample, so you must compare options.

The recipe: define the state, write the recurrence, set base cases, pick the order, then shrink the space if only the last few values matter.

def solve(nums):
n = len(nums)
dp = [0] * (n + 1) # 1. state: dp[i] = answer for the first i items
dp[0] = BASE # 3. base case(s)
for i in range(1, n + 1): # 4. order: smaller subproblems first
dp[i] = combine(dp[i - 1], ...) # 2. recurrence: from earlier states
return dp[n]
# 5. if dp[i] reads only dp[i-1], dp[i-2]: keep two variables instead

The hard part is step 1. Say it in words first: “dp[i] is the best answer for …”.