Sub topic 7
Shrinking from the Ends
This chapter assumes you already know three ideas from earlier chapters. The first is what an interval state dp[i][j] means. The second is how base cases cover single-element and empty ranges. The third is why tables are filled in order of increasing interval length. In the split-point recurrence you tried every k between i and j. Here you will learn a second, cheaper recurrence shape. It applies when every decision touches only the leftmost or rightmost element of the current range.
The Shape of the Recurrence
In an endpoint-shrinking recurrence, dp[i][j] is computed from at most three smaller intervals:
dp[i + 1][j]: the left end has been consumed.dp[i][j - 1]: the right end has been consumed.dp[i + 1][j - 1]: both ends have been consumed together.
Each transition does constant work. There are about n²/2 intervals, so the whole table costs O(n²) time. The split-point recurrence costs O(n³) because it loops over every k.
When the shape applies
Check for these properties in a problem:
- The input is a sequence, and the process removes, matches, or reads elements only from the two ends of what remains.
- What remains after each step is still one contiguous range.
- The value of a step depends only on the endpoint chosen and on facts derived from
(i, j), such as how many elements are left.
If a step can remove an element from the middle, or the range splits into two independent pieces, you need a split-point recurrence instead.
Example 1: Selling Items from Either End
You have a row of items with prices prices[0..n-1]. Each day you sell exactly one item, taken from the left end or the right end of the row. An item sold on day t (counting from 1) earns t * prices[x]. Your goal is to maximize total revenue.
The state is dp[i][j], the maximum revenue from selling the items in the inclusive range i..j, given that the items outside this range are already sold. You don't need to store the day in the state, because it follows from the interval. The range holds j - i + 1 items and n - (j - i + 1) items are already gone, so today is day n - (j - i).
The recurrence is:
- Sell the left item:
day * prices[i] + dp[i + 1][j] - Sell the right item:
day * prices[j] + dp[i][j - 1] dp[i][j]is the larger of the two.
For the base case, a single item i..i is the last one sold, so it is sold on day n.
def max_end_sale_revenue(prices):
n = len(prices)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = n * prices[i] # the last item is sold on day n
for j in range(i + 1, n):
day = n - (j - i) # items already sold: n - (j - i + 1)
take_left = day * prices[i] + dp[i + 1][j]
take_right = day * prices[j] + dp[i][j - 1]
dp[i][j] = max(take_left, take_right)
return dp[0][n - 1]
print(max_end_sale_revenue([2, 3, 5, 1, 4])) # 50The optimal order for [2, 3, 5, 1, 4] sells 2, 4, 1, 3, 5 on days 1 to 5: 2 + 8 + 3 + 12 + 25 = 50. A greedy rule that always sells the cheaper end gives 49. It sells 2, 3, 4, 1, 5, which wastes day 3 on the 4 and leaves the 1 for day 4. Greedy fails because a choice now changes which elements are exposed later. The DP accounts for that by comparing complete futures.
Example 2: A Two-Player Game on the Ends
Two players alternate turns taking a number from either end of an array. Both play optimally. How much more does the first player collect than the second?
Use the state dp[i][j], the best score difference (current player minus opponent) for whoever moves next on nums[i..j]. This is a minimax recurrence written compactly. After you take an end, the opponent becomes the "current player" on the smaller range, so you subtract their best difference:
def first_player_margin(nums):
n = len(nums)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = nums[i]
for j in range(i + 1, n):
dp[i][j] = max(nums[i] - dp[i + 1][j],
nums[j] - dp[i][j - 1])
return dp[0][n - 1]
print(first_player_margin([1, 5, 233, 7])) # 222A first player who greedily takes the larger end (7) loses badly. The correct move is to take 1. The opponent must then expose 233 whichever end they take. The table records exactly this kind of lookahead:
| Interval | Values | dp (mover's margin) |
|---|---|---|
| 1..2 | 5, 233 | 228 |
| 2..3 | 233, 7 | 226 |
| 0..2 | 1, 5, 233 | max(1 − 228, 233 − 4) = 229 |
| 1..3 | 5, 233, 7 | max(5 − 226, 7 − 228) = −221 |
| 0..3 | 1, 5, 233, 7 | max(1 − (−221), 7 − 229) = 222 |
Base Cases and the Empty Interval
Endpoint recurrences that use the "drop both ends" branch, dp[i + 1][j - 1], hit a subtle case when j = i + 1. The inner interval is then i + 1..i, which is empty. With inclusive bounds this cell lies below the main diagonal of the table.
| Situation | Cell read | What it should hold |
|---|---|---|
| Single element | `dp[i][i]` | Set explicitly from the problem |
| Length 2, drop both ends | `dp[i + 1][i]` | The value of an empty range (usually 0) |
| Length 2, drop one end | `dp[i + 1][i + 1]` or `dp[i][i]` | Already computed single-element values |
Zero-initializing the table makes the empty case free when an empty range is worth 0. If you initialize with -inf or inf for a max or min problem, the cells below the diagonal carry that sentinel. Length-2 intervals then read garbage. You have two safe fixes: special-case j == i + 1, or explicitly set the empty cells to their correct value.
Evaluation Order
Each cell depends on cells with a larger i, a smaller j, or both. Two orders satisfy this:
- By length. Process all intervals of length 1, then length 2, and so on. This is the order from the previous chapters, and it works for any interval DP.
- Row by row, bottom-up. Iterate
ifromn - 1down to 0, and inside that iteratejfromi + 1up ton - 1. When you reach(i, j), rowi + 1is already complete, anddp[i][j - 1]was filled one step earlier in the same row.
The examples above use the second order. It is shorter and reads memory row by row. The common mistake is iterating i upward. Then dp[i + 1][j] is still zero when you read it, and the program returns a wrong number without crashing.
Saving Space with a Rolling Row
Row i reads only row i + 1 and itself, so one 1D array is enough. Before you overwrite dp[j], it still holds dp[i + 1][j]. The entry dp[j - 1] already holds the new dp[i][j - 1].
def first_player_margin_1d(nums):
n = len(nums)
dp = [0] * n
for i in range(n - 1, -1, -1):
dp[i] = nums[i]
for j in range(i + 1, n):
dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1])
return dp[n - 1] if n else 0
print(first_player_margin_1d([1, 5, 233, 7])) # 222This cuts space from O(n²) to O(n). The cost is that you lose the full table, so you can no longer trace back which end was chosen at each step. A recurrence that reads dp[i + 1][j - 1] needs one extra saved variable, because that value is overwritten before you need it.
Endpoint vs. Split-Point Recurrences
| Aspect | Endpoint-shrinking | Split-point |
|---|---|---|
| Transitions per cell | O(1) | O(j − i) |
| Total time | O(n²) | O(n³) |
| Structure of a step | Consumes or matches one or both ends | Divides the range into two independent parts |
| Typical problems | End-removal games, end-selling, palindromes | Matrix chains, merging piles, burst balloons |
| 1D space reduction | Usually possible | Rarely possible |
Many problems that look like they need splits are really endpoint problems, and the reverse also happens. Ask what a single step actually does to the remaining range.
Exercise
In maxendsale_revenue, why is the base case dp[i][i] = n prices[i] and not 1 prices[i]?
Show answer
The state i..i means every other item has already been sold, so this item is the last one sold and its sale happens on day n. The day comes from the interval: n - (j - i) = n when i = j.
Exercise
A student rewrites firstplayermargin with the outer loop as "for i in range(n)" (i increasing) and keeps everything else. For nums = [1, 5, 233, 7], what goes wrong and why?
Show answer
When the code computes dp[i][j], it reads dp[i + 1][j], which has not been filled yet and is still 0. The program runs without error but returns a wrong margin. Endpoint recurrences need i to be processed in decreasing order, or the table must be filled by increasing length.
Exercise
Modify the game so that on each turn a player may take one number from the left end, one from the right end, or both end numbers at once (only if at least two remain). Write the new recurrence for dp[i][j].
Show answer
dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1], nums[i] + nums[j] - dp[i+1][j-1]) for j > i, with dp[i][i] = nums[i]. When j = i + 1, the inner range i+1..i is empty and its value must be 0, which a zero-initialized table already provides.