1D Dynamic Programming
How to solve optimisation and counting problems on a line with a one-dimensional table, how to shrink it to O(1) space, and what interviewers ask.
On this page
One-dimensional dynamic programming solves a problem on a sequence by computing the answer for each prefix of the input, from the shortest prefix to the longest, and storing the results in a single row of cells. Each cell is computed from a few earlier cells. You reach for it when a choice at one position affects which choices are allowed at nearby positions, so that picking the best item at each step does not give the best total.
Take shifts that pay 5, 9, 6, 1 and 4 on five days in a row, where you may not work two days in a row. A greedy approach takes the 9 first, which rules out the 5 and the 6, and ends with 9 + 4 = 13. The best plan is 5 + 6 + 4 = 15. The table compares each day with its neighbours and finds it.
How the table is built
The general recipe is in Introduction to Dynamic Programming. For the shift problem it works out like this.
- State.
best[i]is the most you can earn using only days 0 toi. - Recurrence. On day
iyou either rest or work. If you rest, you keepbest[i − 1]. If you work, you earnpay[i]and dayi − 1must be free, so you addbest[i − 2]. The cell is the larger of the two:best[i] = max(best[i − 1], pay[i] + best[i − 2]). - Base cases.
best[0] = pay[0], andbest[1] = max(pay[0], pay[1]), because days 0 and 1 are adjacent and you can take only one. - Order. Each cell reads the two cells to its left, so fill the table from left to right.
- Answer.
best[n − 1].
The two options cover every possible plan. A plan that skips day i is a plan for the earlier days, and the best of those is best[i − 1]. A plan that works day i is, apart from that day, a plan for days 0 to i − 2, and the best of those is best[i − 2].
Filling the table by hand
best[0] = pay[0]best[1] = max(pay[0], pay[1])for i from 2 to n - 1: rest = best[i - 1] work = pay[i] + best[i - 2] best[i] = max(rest, work)return best[n - 1]- pay05i19263144best05i1234
1The first base case is
best[0] = 5, because with only day 0 available you work it. - pay0519i263144best0519i234
2Days 0 and 1 are adjacent, so you take the better one:
best[1] = max(5, 9) = 9. - pay051926i3144best0519211i34
- rest
- 9
- work
- 11
3Day 2 pays 6. Resting keeps 9, and working gives 6 +
best[0]= 11, sobest[2] = 11. - pay05192631i44best0519211311i4
- rest
- 11
- work
- 10
4Day 3 pays 1. Resting keeps 11, and working gives 1 +
best[1]= 10, so resting wins because a pay of 1 is not worth giving up day 2. - pay0519263144ibest0519211311415i
- rest
- 11
- work
- 15
5Day 4 pays 4. Resting keeps 11, and working gives 4 +
best[2]= 15, sobest[4] = 15. - pay0519263144best0519211311415
- answer
- 15
6The answer is
best[4] = 15, from working days 0, 2 and 4. The table took five cells with one comparison each.
To find which days were worked, walk back from the last cell. If a cell equals the cell to its left, that day was a rest day, so move one cell left. If it is larger, that day was worked, so record it and move two cells left. Here 15 is larger than 11, so day 4 is worked and you move to best[2]. Then 11 is larger than 9, so day 2 is worked and you move to best[0], which is day 0.
Code
function maxPay(pay) {
const n = pay.length;
if (n === 0) return 0;
if (n === 1) return pay[0];
const best = new Array(n);
best[0] = pay[0];
best[1] = Math.max(pay[0], pay[1]);
for (let i = 2; i < n; i++) {
const rest = best[i - 1];
const work = pay[i] + best[i - 2];
best[i] = Math.max(rest, work);
}
return best[n - 1];
}
maxPay([5, 9, 6, 1, 4]); // 15def max_pay(pay):
n = len(pay)
if n == 0:
return 0
if n == 1:
return pay[0]
best = [0] * n
best[0] = pay[0]
best[1] = max(pay[0], pay[1])
for i in range(2, n):
rest = best[i - 1]
work = pay[i] + best[i - 2]
best[i] = max(rest, work)
return best[n - 1]
max_pay([5, 9, 6, 1, 4]) # 15Each step reads only the two most recent cells, so the array can be replaced by two variables. Starting both at 0 also removes the special cases, because the best total before any days is 0.
function maxPayLowMemory(pay) {
let twoBack = 0; // best up to day i - 2
let oneBack = 0; // best up to day i - 1
for (const p of pay) {
const current = Math.max(oneBack, p + twoBack);
twoBack = oneBack; // slide the window right by one day
oneBack = current;
}
return oneBack;
}def max_pay_low_memory(pay):
two_back = 0 # best up to day i - 2
one_back = 0 # best up to day i - 1
for p in pay:
current = max(one_back, p + two_back)
two_back = one_back # slide the window right by one day
one_back = current
return one_backComplexity
| Approach | Time | Space | Why |
|---|---|---|---|
| Table | O(n) | O(n) | There are n cells and each takes one comparison. |
| Two variables | O(n) | O(1) | The work is the same, but only the last two cells are kept. |
Write the table version first and shrink it once it works. The shrunk version cannot walk back to list the chosen days, because the earlier cells are gone.
Variants
Counting ways instead of maximising
The recurrence does not have to take a maximum. Suppose you climb 6 steps with strides of 1, 2 or 3 steps, and want the number of stride sequences that reach the top. Let ways[i] be the number of ways to stand on step i. The last stride came from step i − 1, i − 2 or i − 3, and these cases never overlap, so you add them: ways[i] = ways[i − 1] + ways[i − 2] + ways[i − 3], ignoring any index below 0. The base case is ways[0] = 1, and the table is filled upward to ways[6].
| step i | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| ways[i] | 1 | 1 | 2 | 4 | 7 | 13 | 24 |
function countClimbs(steps) {
const ways = new Array(steps + 1).fill(0);
ways[0] = 1; // standing at the bottom: one way, do nothing
for (let i = 1; i <= steps; i++) {
for (const stride of [1, 2, 3]) {
if (i - stride >= 0) ways[i] += ways[i - stride];
}
}
return ways[steps];
}
countClimbs(6); // 24def count_climbs(steps):
ways = [0] * (steps + 1)
ways[0] = 1 # standing at the bottom: one way, do nothing
for i in range(1, steps + 1):
for stride in (1, 2, 3):
if i - stride >= 0:
ways[i] += ways[i - stride]
return ways[steps]
count_climbs(6) # 24Counting works only if every sequence is counted exactly once. Here that holds because each sequence has exactly one last stride. If the problem asks for combinations where the order of strides does not matter, the same recurrence over-counts, because it treats 1 then 2 and 2 then 1 as different. The loops then have to be arranged so that each combination is built in only one order.
Minimising a cost
When the question asks for the cheapest way, replace max with min. For a staircase where each step has a toll and you may climb one or two steps at a time, cost[i] = toll[i] + min(cost[i − 1], cost[i − 2]). The only extra care is the base cases and the exact meaning of the answer, for example whether you must stand on the last step or only get past it.
A state that ends exactly at position i
Sometimes the prefix answer cannot be extended, because the next element must connect to the previous one. In maximum subarray, a sum that skips element i − 1 cannot be extended by element i, so the state is defined as end[i], the best sum of a subarray that ends exactly at i. The recurrence is end[i] = nums[i] + max(0, end[i − 1]), which means you either start a new subarray at i or extend the previous one. The best subarray can end anywhere, so the answer is the largest value in the whole table, not the last cell.
Choosing items on a circle
If the days form a circle, so that the last day is also adjacent to the first, the single table no longer works, because the first and last days cannot both be worked and the table does not know which one was chosen. The fix is to solve the problem twice, once on days 0 to n − 2 and once on days 1 to n − 1, and take the larger result. For pays 5, 9, 6, 1, 4 the first range gives 11 and the second gives 13, so the answer is 13. A circle with one element has to be handled separately, returning that element.
When 1D dynamic programming does not apply
A prefix is not enough information when the allowed choices depend on more than the last few positions. If the rule is "at most k days in total" or "no more than two days in a row", the state needs an extra number, and the table gains a second dimension or a small set of extra states for each day. When the choices are independent and each one has a fixed value, such as "take every positive number", a single pass is enough and no table is needed. When the problem is not laid out on a line, for example choosing items under a weight limit, see Knapsack instead.
Pitfalls
In the interview
Three signals in the problem statement point to 1D dynamic programming. The input is a line of items, such as an array, a string or a count of steps. The task is to maximise, minimise or count something. And the choice at one position restricts the choices at the next one or two positions, which is the reason greedy fails. Classic forms are house robber, climbing stairs, minimum cost climbing stairs, decoding a string of digits into letters and maximum subarray.
Say the state in words before writing code: "best[i] is the best total using the first i + 1 days." Then state the recurrence, the base cases and the order. Interviewers listen for this more than for the code.
Questions to expect:
- "Why not just take the largest values?" Taking the 9 in the example blocks both of its neighbours and leads to 13, while the best plan is 15. A local choice can cost more than it earns, and the table is what compares the alternatives.
- "Can you reduce the space?" Yes. Each cell reads only the previous two, so two variables are enough and the space drops from O(n) to O(1). The cost is that you can no longer reconstruct which items were chosen.
- "How would you return the chosen days, not just the total?" Keep the full table, then walk back from the last cell. If a cell equals the one on its left, that day was skipped. Otherwise it was worked, so record it and jump two cells left.
- "What if the days form a circle?" Solve the line twice, once without the first day and once without the last day, and return the larger answer. This works because the first and last day can never both be used.
- "Is this the same as recursion with memoization?" It computes the same values. Memoization starts from the answer and fills in only the cells it needs, and the table version fills every cell in order. The recursive version can hit the recursion limit on long input, which is a reason to prefer the table.
- "What is the complexity?" The time is O(n) because each of the n cells is computed once with constant work. The space is O(n) for the table and O(1) with two variables. If each cell tries k earlier cells, as in the stride problem, the time is O(n · k).
Shifts pay [2, 7, 9, 3, 1], and you may not work two days in a row. What is best[4]?
Strides can be 1 or 2 steps. How many ways are there to climb 4 steps?
Why can the shift problem keep two variables instead of a whole array?
What to practise next
Practise both shapes with Sunny Orchard Row, which uses the no-two-in-a-row rule, and Stepping Stones Across the Pond, which counts ways. Then DP on Grids extends the same recipe to two dimensions.