Command Palette

Search for a command to run...

← All patterns

Pattern · Dynamic Programming

1D Dynamic Programming

Define dp[i] as the answer for the first i items, write how it depends on smaller i, and fill it left to right.

Time O(n) · Space O(n), often O(1) with two variables

Taught in Module 28: DP Foundations: 1D

Think of it like this

Climbing stairs and writing on each step how many ways there are to reach it: each number comes from the one or two steps below.

Clues that point here

  • → Count the ways
  • → Maximum or minimum over choices at each step
  • → "You can't take two adjacent"
  • → Recursion with repeated subproblems

Not this pattern when

  • ✕ Choices interact across far-apart positions (2D or interval DP)
  • ✕ A greedy choice is provably safe

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

1D Dynamic Programming · template
int[] dp = new int[n + 1];
dp[0] = base0; dp[1] = base1;
for (int i = 2; i <= n; i++) {
    dp[i] = Math.max(dp[i - 1], dp[i - 2] + value[i - 1]);   // the recurrence
}
return dp[n];

Common versions

  • Climbing stairs
  • House robber
  • Decode ways
  • Min cost climbing stairs
  • Word break

Practice problems with this pattern

Related patterns