One-Dimensional Dynamic Programming
A DP whose state is a single index. You keep one array, each entry is the answer for a prefix (or for the position i), and each entry is computed from a few entries before it.
What Makes a DP One-Dimensional
In 1d dp, everything you need to know about a subproblem fits in one number: an index into the input, or an amount like a capacity or a target. So the table is a single array, dp[0..n], filled from left to right. Climbing stairs, the houses problem in the tracer below, decode ways and longest increasing subsequence are all of this kind.
The work is not in the array; it is in choosing what dp[i] means. Once that sentence is right, the recurrence usually follows from asking what happened at position i. If you cannot describe the answer to a subproblem with one index, the state needs a second dimension, which is two-dimensional dynamic programming.
- Input: usually a sequence (array, string) or a single number n
- Table: one entry per position or amount
- Answer: dp[n − 1], dp[n], or the maximum over all dp[i], depending on what dp[i] means
Designing dp[i] and Its Recurrence
- Write one sentence: dp[i] is the ... for ...
- List the choices at position i and the smaller dp each one leaves
- Combine them: max or min for optimisation, + for counting
- Set the base cases that the first few cells need (dp[0], and dp[1] if the recurrence reaches back two)
- Fill i from left to right and read the answer from the right place
There are two common meanings for dp[i], and mixing them up is the most common bug in one dimensional dynamic programming. The prefix meaning says dp[i] is the best answer using items 0 to i, wherever the solution ends; the answer is then the last cell. The ending-here meaning says dp[i] is the best answer for a solution that ends exactly at i; the answer is then the largest cell. The houses problem uses the first; longest increasing subsequence and Kadane's algorithm use the second.
With the meaning fixed, look at position i and list the choices for it. For the houses: house i is skipped (dp[i − 1]) or taken (money[i] + dp[i − 2]). For stairs: the last step was 1 or 2 (dp[i − 1] + dp[i − 2]). The recurrence is just those choices combined with max, min or +.
- Check the recurrence by hand on 3 or 4 elements before coding
- Use size n + 1 with dp[0] as the 'empty prefix' when it makes base cases disappear
Three 1D DP Patterns
Most problems fall into one of three 1d dp patterns, and the pattern tells you the cost before you write anything. The diagram above shows the first and third side by side.
- Fixed look-back: dp[i] reads dp[i − 1] and dp[i − 2] (or a few more). Stairs, Fibonacci-style counts, decode ways. O(n) time, O(1) space with rolling variables
- Take or skip: dp[i] = best of skipping i (dp[i − 1]) or taking it and jumping past its conflicts (dp[i − 2] + value). The houses problem. Still a fixed look-back, still O(1) space
- Look back over all j < i: dp[i] = best over every earlier j that can lead to i. Longest increasing subsequence, word break, jump game counts. O(n²) time, and the full array must stay
Terms, operations, and practical uses
Key terms
- StateWhat dp[i] stands for, said in one sentence.
- Prefix statedp[i] is the best for items 0..i; the answer is the last cell.
- Ending-here statedp[i] is the best for a solution that ends at i; the answer is the maximum cell.
- Rolling variablesKeeping only the last few cells when nothing older is read.
Related lessons and problems
- Dynamic ProgrammingThe two conditions and the general method.
- Memoization vs TabulationTop-down or bottom-up for the same recurrence.
- Grid Dynamic ProgrammingThe next step: one cell per grid square.
- House Robber (problem)The tracer's problem with tests.
- Climbing Stairs (problem)The simplest fixed look-back.
Code in Python, C++ and Java
def best_table(houses):
n = len(houses)
if n == 0:
return []
dp = [0] * n
dp[0] = houses[0]
for i in range(1, n):
skip = dp[i - 1]
take = houses[i] + (dp[i - 2] if i >= 2 else 0)
dp[i] = max(skip, take)
return dp
def best_rolling(houses):
two_back, one_back = 0, 0
for money in houses:
two_back, one_back = one_back, max(one_back, two_back + money)
return one_back
def alternate(houses):
return max(sum(houses[0::2]), sum(houses[1::2]))
houses = [2, 7, 9, 3, 1]
print("houses:", houses)
print("dp:", best_table(houses))
print("best:", best_table(houses)[-1], "rolling:", best_rolling(houses))
print("[2, 1, 1, 2] dp:", best_rolling([2, 1, 1, 2]), "every other house:", alternate([2, 1, 1, 2]))
print("[5]:", best_rolling([5]), "[]:", best_rolling([]))#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
vector<int> bestTable(const vector<int>& houses) {
int n = houses.size();
vector<int> dp(n, 0);
if (n == 0) return dp;
dp[0] = houses[0];
for (int i = 1; i < n; i++) {
int skip = dp[i - 1];
int take = houses[i] + (i >= 2 ? dp[i - 2] : 0);
dp[i] = max(skip, take);
}
return dp;
}
int bestRolling(const vector<int>& houses) {
int twoBack = 0, oneBack = 0;
for (int money : houses) {
int next = max(oneBack, twoBack + money);
twoBack = oneBack;
oneBack = next;
}
return oneBack;
}
int alternate(const vector<int>& houses) {
int even = 0, odd = 0;
for (size_t i = 0; i < houses.size(); i++) (i % 2 ? odd : even) += houses[i];
return max(even, odd);
}
void print(const char* name, const vector<int>& v) {
printf("%s [", name);
for (size_t i = 0; i < v.size(); i++) printf("%s%d", i ? ", " : "", v[i]);
printf("]\n");
}
int main() {
vector<int> houses = {2, 7, 9, 3, 1};
print("houses:", houses);
vector<int> dp = bestTable(houses);
print("dp:", dp);
printf("best: %d rolling: %d\n", dp.back(), bestRolling(houses));
vector<int> tricky = {2, 1, 1, 2};
printf("[2, 1, 1, 2] dp: %d every other house: %d\n", bestRolling(tricky), alternate(tricky));
printf("[5]: %d []: %d\n", bestRolling({5}), bestRolling({}));
}import java.util.Arrays;
public class Main {
static int[] bestTable(int[] houses) {
int n = houses.length;
int[] dp = new int[n];
if (n == 0) return dp;
dp[0] = houses[0];
for (int i = 1; i < n; i++) {
int skip = dp[i - 1];
int take = houses[i] + (i >= 2 ? dp[i - 2] : 0);
dp[i] = Math.max(skip, take);
}
return dp;
}
static int bestRolling(int[] houses) {
int twoBack = 0, oneBack = 0;
for (int money : houses) {
int next = Math.max(oneBack, twoBack + money);
twoBack = oneBack;
oneBack = next;
}
return oneBack;
}
static int alternate(int[] houses) {
int even = 0, odd = 0;
for (int i = 0; i < houses.length; i++) {
if (i % 2 == 0) even += houses[i]; else odd += houses[i];
}
return Math.max(even, odd);
}
public static void main(String[] args) {
int[] houses = {2, 7, 9, 3, 1};
System.out.println("houses: " + Arrays.toString(houses));
int[] dp = bestTable(houses);
System.out.println("dp: " + Arrays.toString(dp));
System.out.println("best: " + dp[dp.length - 1] + " rolling: " + bestRolling(houses));
int[] tricky = {2, 1, 1, 2};
System.out.println("[2, 1, 1, 2] dp: " + bestRolling(tricky) + " every other house: " + alternate(tricky));
System.out.println("[5]: " + bestRolling(new int[] {5}) + " []: " + bestRolling(new int[] {}));
}
}Step through it
Running on money in houses [2, 7, 9, 3, 1]
Rolling Variables and Complexity
When dp[i] reads only the last k cells, keep those k values and slide them forward: new = f(one back, two back), then two back = one back and one back = new. Time stays O(n), space drops from O(n) to O(k). The tracer ends with this version.
Rolling throws away the history, so it cannot answer which choices produced the best value. If the question asks for the actual houses, the actual subsequence or the split points, keep the array (or a parent array) and walk back from the answer, as the tracer's payoff step does.
- Fixed look-back k: O(n) time, O(k) space
- All j < i: O(n²) time, O(n) space; some problems speed this up with binary search (LIS in O(n log n))
- Amount-indexed arrays, as in unbounded knapsack, are 1D too: O(n·W) time, O(W) space
Common Mistakes
A 1D DP is short enough that bugs hide in a single line. Most come from the base cases or from reading the answer out of the wrong cell.
- Wrong second base case: for the houses, dp[1] = max(money[0], money[1]), not money[1]
- Ending-here state but answer taken from the last cell; take the maximum instead
- Guessing a pattern (every other house) instead of trying both choices: [2, 1, 1, 2] gives 3 by alternating, 4 by DP
- Updating the rolling variables in the wrong order, so 'two back' gets the new value
- Forgetting n = 0 and n = 1 inputs, where dp[1] does not exist
1D DP Problems to Practise
These problems are roughly in order of difficulty. The first four are fixed look-back, the rest look back further or need two states per index.
- Climbing Stairs and Min Cost Climbing Stairs: two cells back
- House Robber: the tracer's take-or-skip problem
- House Robber II: houses in a circle, solved by running the line version twice
- Decode Ways: one or two characters back, with validity checks
- Word Break and Longest Increasing Subsequence: look back over all j
- Maximum Product Subarray: two values per index, the largest and the smallest