Learn the pattern · ~14 min
1D / Fibonacci-style
also called linear DP, DP over prefixes
Write down one number per position, the best answer for everything up to it, and build each new number from the last one or two.
Reach for it when you read
- +Items in a line, a take-or-skip choice at each, and taking one forbids its neighbour (or the next few).
- +"How many ways to reach step n" when each move goes back a fixed 1, 2 or k steps.
- +"Min / max cost to reach the end" where position i is reached only from a few earlier positions.
- +Split a string from the left ("decode", "break into words"): the answer for the first i letters reads a few shorter prefixes.
- +Your recursion has one argument, the index, and calls itself on i − 1 and i − 2.
Not this one when
- ×Each step depends on every earlier element (longest increasing subsequence): still 1-D, but O(n²) or the tails trick.
- ×Two indices move independently, like two strings or a grid: 2-D DP.
- ×A budget or target sum comes along with the index: knapsack, the state needs the amount too.
Learn 1D / Fibonacci-style
First, what does "dynamic programming" mean?
Take Fibonacci: f(5) = f(4) + f(3), and f(4) = f(3) + f(2). Both f(5) and f(4) need f(3). A plain recursion works out f(3) twice and f(2) three times: 15 calls for a tiny number.
Dynamic programming (DP) fixes that: when a big question is built from smaller ones, and the same small question keeps coming back, answer each one once and write it down.
1-D DP means each small question is named by one number, usually an index: "the best for the first i items". The answers fit in one array, dp[0..n−1].
The problem: rob a street
Six houses in a row hold [5, 1, 2, 9, 3, 4]. You can't rob two houses that are next to each other. What's the most you can take?
Try a few legal picks by hand:
| houses robbed | money | how you found it |
|---|---|---|
| 0, 2, 4 | 5 + 2 + 3 = 10 | every other house, starting at 0 |
| 1, 3, 5 | 1 + 9 + 4 = 14 | every other house, starting at 1 |
| 0, 3 | 5 + 9 = 14 | the two big ones, gap of two |
| 0, 3, 5 | 5 + 9 + 4 = 18 | the two big ones, then 4 still fits |
The answer is 18; "every other house" gives only 10 or 14. There are 20 legal picks here, and the count explodes as the street grows.
One choice per house
Stand at the last house, i = 5, holding 4. There are only two things you can do:
Skip house i, or rob it and stay away from house i − 1.
Write best(i) for "the most money from houses 0..i". Then:
| choice at house 5 | what happens | money |
|---|---|---|
| skip it | houses 0..4 are all still allowed | best(4) |
| rob it | take 4; house 4 is off limits, 0..3 are left | 4 + best(3) |
So best(5) = max(best(4), 4 + best(3)). The same holds at every house: best(i) = max(best(i − 1), a[i] + best(i − 2)). When i < 0 there are no houses: best(i) = 0.
The brute force: the plain recursion
That rule is already a program:
// best(i) = the most money from houses 0..i
int best(int i, const vector<int>& a) {
if (i < 0) return 0; // no houses left
return max(best(i - 1, a), // skip house i
a[i] + best(i - 2, a)); // rob it, so its neighbour is off limits
}It returns 18. The top of its call tree:
- best(5)
- skip: best(4)
- skip: best(3)
- skip: best(2) …
- rob: best(1) …
- rob: best(2) …
- rob: best(3)
- skip: best(2) …
- rob: best(1) …
Every call makes two more, so the tree grows like Fibonacci: 41 calls for 6 houses, 5.4 × 10⁸ for 40 (half a second), 5.9 × 10⁹ for 45 (5 seconds). House Robber allows 100 houses. Time limit exceeded.
The one thought: the same question comes back
best(3) appears twice in the tree: on the path "skip 5, skip 4" and on "rob 5".
Is it the same question both times? Yes: "the most from houses 0..3". What you did at houses 4 and 5 doesn't change which of houses 0..3 you may rob, so the answer is 14 either way.
Lower down it gets worse: best(2) is worked out 3 times, best(1) 5 times, best(0) 8 times. Yet there are only 6 different questions, best(0) to best(5).
So keep a notebook. The first time you answer best(i), write it in memo[i]; every later time, read it.
int best(int i, const vector<int>& a, vector<int>& memo) {
if (i < 0) return 0;
if (memo[i] != -1) return memo[i]; // asked before: answer from the notebook
return memo[i] = max(best(i - 1, a, memo),
a[i] + best(i - 2, a, memo));
}Start memo full of −1 ("not answered yet"). Now each best(i) is computed once: 13 calls instead of 41, about 2n for any n. This top-down version is memoisation.
Bottom-up: fill the table left to right
best(i) only needs smaller indices, so skip the recursion and fill the answers smallest first: by the time you reach i, both cells it needs are done.
int robTable(const vector<int>& a) {
int n = a.size();
if (n == 1) return a[0];
vector<int> dp(n); // dp[i] = best for houses 0..i
dp[0] = a[0];
dp[1] = max(a[0], a[1]);
for (int i = 2; i < n; i++)
dp[i] = max(dp[i - 1], a[i] + dp[i - 2]); // skip, or rob
return dp[n - 1];
}| i | house | what happens | dp[i] |
|---|---|---|---|
| 0 | 5 | one house: rob it | 5 |
| 1 | 1 | two houses, take the bigger: max(5, 1) | 5 |
| 2 | 2 | skip: dp[1] = 5. Rob: 2 + dp[0] = 7. Rob wins | 7 |
| 3 | 9 | skip: dp[2] = 7. Rob: 9 + dp[1] = 14. Rob wins | 14 |
| 4 | 3 | skip: dp[3] = 14. Rob: 3 + dp[2] = 10. Skip wins | 14 |
| 5 | 4 | skip: dp[4] = 14. Rob: 4 + dp[3] = 18. Rob wins | 18 |
18, the same answer as the brute force. Notice row 4: robbing can lose. 3 + 7 is less than 14, so houses 0..4 keep the old 14.
Down to two variables
Row i reads only rows i − 1 and i − 2, so keep just those two numbers:
int rob(const vector<int>& a) {
int prev2 = 0, prev1 = 0; // best up to i - 2, best up to i - 1
for (int x : a) {
int cur = max(prev1, prev2 + x);
prev2 = prev1;
prev1 = cur;
}
return prev1;
}| x | prev2 | prev1 | cur = max(prev1, prev2 + x) |
|---|---|---|---|
| 5 | 0 | 0 | 5 |
| 1 | 0 | 5 | 5 |
| 2 | 5 | 5 | 7 |
| 9 | 5 | 7 | 14 |
| 3 | 7 | 14 | 14 |
| 4 | 14 | 14 | 18 |
The same numbers as the table, without the table. Starting both at 0 also handles n = 1.
Why it's O(n)
Count the questions, not the loops: n of them, each decided by one max of two numbers you already have. So O(n) time. Space is O(n) for the memo or the table, and O(1) with two variables.
From about 1.6ⁿ calls down to n steps, by never answering the same question twice.
Climbing Stairs? Count instead of max
How many ways to climb 5 steps, taking 1 or 2 at a time? The last move was a 1-step (from step i − 1) or a 2-step (from step i − 2). Different ways, so add them:
vector<long long> ways(n + 1);
ways[0] = ways[1] = 1; // one way to stand still, one way to climb 1
for (int i = 2; i <= n; i++)
ways[i] = ways[i - 1] + ways[i - 2]; // last move was 1 step, or 2 stepsThe counts go 1, 1, 2, 3, 5, 8: 8 ways. Same shape as House Robber, with + in place of max.
Houses in a circle? Run the line twice
House Robber II puts the houses in a circle, so house 0 and house n − 1 become neighbours. Never use both: solve houses 0..n − 2, then 1..n − 1, and take the better.
int robCircle(const vector<int>& a) {
int n = a.size();
if (n == 1) return a[0];
vector<int> noLast(a.begin(), a.end() - 1), noFirst(a.begin() + 1, a.end());
return max(rob(noLast), rob(noFirst));
}On our street both runs give 14: the old 18 used houses 0 and 5, which now touch.
Decode Ways? A move that's allowed only sometimes
"226" decodes as 2 2 6, 22 6 or 2 26. dp[i] = ways to decode the first i letters, with dp[0] = 1. Add dp[i − 1] only if the last letter isn't 0, and dp[i − 2] only if the last two read 10 to 26. The table goes 1, 1, 2, 3.
Remember this
- A choice at every item, and the rest of the problem depends only on where you are: the state is one index. Write
dp[i]in words first: "the best for houses 0..i". - The order of work: plain recursion → spot the repeated call → memo → fill the table smallest first → keep only the cells you read.
- Traps: handle n = 1 before reading
dp[1]; the answer is the last cell, never a greedy pick (biggest-first takes 4 from[3, 4, 3], the best is 6). - Whenever a problem walks a line and each position looks back a fixed few steps, it's 1-D DP. If it looks back k steps, keep k variables.
Practise it on Climbing Stairs, then Min Cost Climbing Stairs (min plus a price per step), House Robber, House Robber II (the circle), Decode Ways (moves that are only sometimes legal) and Delete and Earn (add up equal values, then each value is a house).
Below, watch House Robber run line by line.
Watch it work, line by line
House Robber ↗, nums = [2, 7, 9, 3, 1] → 12 (2 + 9 + 1). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Can I define one number per position whose value follows from the last one or two (or a few) positions, and does plain recursion keep recomputing the same position?
Reach for it when
- +count ways / best value along a line
- +choose or skip each element with local constraints
- +string decode / break into words
- +n up to 1e5-1e6 for O(n); 5000 for O(n2)
It fails when
- ×Subproblems don't overlap, each one is uniqueuse Plain recursion / divide & conquer
- ×No optimal substructure: subresults can't be combined into the answeruse Rethink the model; DP doesn't apply
- ×State needs a second axis (a second string, capacity) or modesuse 2-D DP: LCS, knapsack, state machine
- ×A provable greedy exists (jump game)use Greedy
- ×You think greedy works here: robbing the richest house can forfeit two good neighboursuse
max(skip, take + dp[i-2]) - ×The transition takes the best over a sliding range of earlier statesuse DP + monotonic deque
- ×It's a contiguous-subarray constraint, not a recurrence over an indexuse Sliding window
Looks like it, isn't (and the other way round)
- Delete and Earn looks like Greedy, needs this pattern
Taking x deletes x-1 and x+1: after bucketing values it is house robber.
- Word Break looks like Backtracking, needs this pattern
Backtracking repeats suffixes; dp over prefix positions.
- Maximum Number of Events That Can Be Attended II looks like Interval Scheduling (sort by end), needs this pattern
The values break the earliest-end greedy that solves part I. The editorial uses DP with binary search for the next compatible event.
- Maximum Profit in Job Scheduling looks like Interval Scheduling (sort by end), needs this pattern
Weighted interval scheduling: sort by end, dp with binary search for the last compatible job. Greedy by end time fails with weights.
- House Robber III looks like 1D / Fibonacci-style, needs DP on Trees
Same take/skip idea but on a tree: dp[v] = (take, skip) from children.
- Jump Game II looks like 1D / Fibonacci-style, needs Greedy
O(n2) DP works but the greedy BFS over reach windows is O(n).
- Maximum Subarray looks like 1D / Fibonacci-style, needs Kadane's Algorithm
It is DP, but the named O(1)-space form is Kadane's algorithm.
- New 21 Game looks like 1D / Fibonacci-style, needs Probability & Expected-Value DP (linearity of expectation)
The probability DP over points is O(n*maxPts) unless the transition sum is kept as a sliding window.
Why this pattern and not another
The answer at index i depends on a fixed window of earlier answers with overlapping subproblems and interacting choices — solved once each, bottom-up, in O(n).
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What three things do you decide before writing a 1D DP?Reveal
What
dp[i]means, how it's built from earlier cells (the transition), and the base cases you know by hand.2Why is the recursion exponential but the DP linear?Reveal
The recursion solves the same prefix many times; the DP solves each prefix once and reads it from the table.
3When can you replace the dp array with two variables?Reveal
When the transition only reads a fixed number of cells back (here i − 1 and i − 2).
4Before writing a table, which brute force do you write first, and what do you look for in it?Reveal
A recursion that decides about the last item. Then count how often each argument is solved: repeats whose answer depends only on the argument are the subproblems, and the argument becomes the state.
Practice ladder
- 1Climbing Stairscount the waysEasy
- 2Min Cost Climbing Stairspay to moveEasy
- 3House Robberthe hookMedium
- 4Dice Combinationscount the waysEasy
- 5House Robber IIa circleMedium
- 6Decode Waysconditional moveMedium
- 7Delete and Earnchange the axisMedium
- 8Word Breakconditional moveMedium
- 9Maximum Profit in Job Schedulingfar-back jumpHard
Finished 1D / Fibonacci-style? Mark it done and Lessgo moves you to the next step.