Sub topic 13
Thinking Backwards: The Last Operation in an Interval
This chapter assumes you are comfortable with the split-point recurrence, filling tables by increasing interval length, and top-down memoization, all covered in earlier chapters. You should also be able to read recursive Python that uses functools.lru_cache.
Some interval problems look like they should split at a point but will not split cleanly. Choosing the first action in a range leaves behind pieces that still affect each other. The fix is to change which action you pick. You stop asking "what happens first?" and ask "what happens last?" This chapter works through that reframing on the burst balloons problem. It then shows how to tell which framing a new problem needs.
The Problem: Burst Balloons
You are given a row of balloons with values nums. When you burst balloon k, you earn left * nums[k] * right coins. Here left and right are the values of the balloons currently next to k. Balloons that have already burst do not count as neighbors. If there is no neighbor on one side, you treat that side as having value 1. You must burst every balloon. The goal is to find the order that earns the most coins.
For nums = [3, 1, 5, 8] the best total is 167. Here is one optimal order:
| Step | Burst | Neighbors at that moment | Coins |
|---|---|---|---|
| 1 | 1 | 3 and 5 | 3 × 1 × 5 = 15 |
| 2 | 5 | 3 and 8 | 3 × 5 × 8 = 120 |
| 3 | 3 | boundary (1) and 8 | 1 × 3 × 8 = 24 |
| 4 | 8 | boundary (1) and boundary (1) | 1 × 8 × 1 = 8 |
The total is 15 + 120 + 24 + 8 = 167.
Why "Burst First" Fails
The obvious recurrence picks the first balloon k to burst in a range [i, j], earns its coins, and then recurses on [i, k-1] and [k+1, j]. That recurrence is wrong.
When k bursts, balloons k-1 and k+1 become neighbors. Later, bursting k-1 earns coins that depend on k+1, which lives in the other half. The two halves are no longer independent. The value of the left half depends on what is still standing in the right half, and the state dp[i][j] does not record that. The optimal substructure that interval DP depends on is gone.
The Reframing: Choose the Last Balloon
Look at a range from the opposite end of time. Suppose balloon k is the last balloon burst among those strictly between positions left and right. Three things follow:
- At the moment
kbursts, every other balloon in the range is gone. So its neighbors must beleftandrightthemselves, and its gain isvals[left] * vals[k] * vals[right], which is fully determined. - Until that moment,
kis still standing. It acts as a wall. Balloons betweenleftandkonly ever see neighbors inside(left, k)or the wallsleftandk. - The same holds for
(k, right). The two sides never interact, so they are independent subproblems.
This only works if the boundaries are balloons that are guaranteed to outlive the range. That is why the state uses exclusive bounds. best(left, right) means "the most coins from bursting every balloon strictly between left and right, given that left and right are still present." To give the outermost range real walls, pad the array with a 1 on each end. Each padding value is a balloon that is never burst and matches the "missing neighbor counts as 1" rule.
The recurrence is:
best(left, right) = 0whenright == left + 1, because the open interval is empty.- Otherwise,
best(left, right) = max over left < k < right of best(left, k) + vals[left] * vals[k] * vals[right] + best(k, right).
The tree is the 4-step table read from the bottom up. The last burst sits at the root, and the first burst (balloon 1, worth 15) is the deepest leaf.
Top-Down Implementation
from functools import lru_cache
def max_coins(nums):
vals = [1] + nums + [1]
@lru_cache(maxsize=None)
def best(left, right):
# Best total from bursting every balloon strictly between left and right.
result = 0
for k in range(left + 1, right):
gain = vals[left] * vals[k] * vals[right]
result = max(result, best(left, k) + gain + best(k, right))
return result
return best(0, len(vals) - 1)
print(max_coins([3, 1, 5, 8])) # 167The base case is built into the loop. When right == left + 1, range(left + 1, right) is empty and result stays 0. Note that k appears in both recursive calls, best(left, k) and best(k, right). In matrix chain the split is [i, k] and [k+1, j]. Here the split element is shared because it is a wall on both sides, not a member of either sub-interval.
Bottom-Up Implementation
The table version fills intervals by increasing gap right - left. Every sub-interval (left, k) and (k, right) has a smaller gap, so it is ready before it is read.
def max_coins_bottom_up(nums):
vals = [1] + nums + [1]
m = len(vals)
dp = [[0] * m for _ in range(m)]
for gap in range(2, m):
for left in range(0, m - gap):
right = left + gap
best = 0
for k in range(left + 1, right):
cand = dp[left][k] + vals[left] * vals[k] * vals[right] + dp[k][right]
if cand > best:
best = cand
dp[left][right] = best
return dp[0][m - 1]
print(max_coins_bottom_up([3, 1, 5, 8])) # 167Gap 1 is skipped because those entries are the empty-interval base case, and they are already 0. With n balloons there are O(n²) states and O(n) choices of k each, so time is O(n³) and space is O(n²).
Checking Against Brute Force
A reframed recurrence is easy to get subtly wrong, so test it against a direct simulation on small inputs. This brute force tries every order, which takes O(n!) time and is only practical for n up to about 8.
import random
def brute_force(nums):
if not nums:
return 0
best = 0
for i in range(len(nums)):
left = nums[i - 1] if i > 0 else 1
right = nums[i + 1] if i + 1 < len(nums) else 1
rest = nums[:i] + nums[i + 1:]
best = max(best, left * nums[i] * right + brute_force(rest))
return best
for _ in range(300):
nums = [random.randint(0, 9) for _ in range(random.randint(0, 6))]
assert brute_force(nums) == max_coins_bottom_up(nums), nums
print("all tests passed")You Have Seen This Before
Matrix chain multiplication already uses last-operation thinking, without naming it. The split k in dp[i][j] is the last multiplication performed. That product joins the result of A_i..A_k with the result of A_{k+1}..A_j, and its cost dims[i] * dims[k+1] * dims[j+1] depends only on the outer dimensions. Stone merging works the same way: the final merge of i..j always costs the interval's total weight. Burst balloons is harder only because the natural first guess, the first burst, happens to be the wrong framing.
First or Last: Deciding for a New Problem
| Ask yourself | Points toward | Example |
|---|---|---|
| Does the action physically separate the range into parts that never interact again? | First operation | Cutting a stick: the first cut leaves two independent pieces |
| Does the action remove something, so that elements on either side become adjacent? | Last operation | Burst balloons, removing elements with neighbor-dependent cost |
| Does the action combine two finished parts, at a cost that depends on their boundaries or totals? | Last operation | Matrix chain, stone merging, polygon triangulation |
| Does the cost of the chosen action depend on elements that might already be gone? | Last operation, using the range's fixed walls | Burst balloons |
The general test is this: pick the action whose cost is fully determined by the state (i, j) alone, and whose remaining work splits into independent pieces. If the first action fails that test, try the last.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Recursing on `[i, k-1]` and `[k+1, j]` after a "first burst" | Answers too high or too low on small cases | Switch to last-burst with exclusive bounds |
| Forgetting the padding 1s | Index errors, or wrong gains at the ends | Build `vals = [1] + nums + [1]` and solve `(0, len(vals) - 1)` |
| Using inclusive bounds with the last-burst gain | Gain uses `vals[i-1]` and `vals[j+1]`, causing off-by-one errors | Keep both bounds exclusive so the walls are the bounds themselves |
| Iterating `left` upward with fixed `right` in bottom-up | Reads `dp[k][right]` before it is computed | Loop over gap length on the outside |
| Dropping zero-valued balloons as an "optimization" | Correct here, but it is easy to break the indexing | Only filter before padding, and test against brute force |
Exercise
Compute max_coins([1, 5]) by hand using the last-burst recurrence. Which balloon is burst last, and what is the total?
Show answer
Padded vals = [1, 1, 5, 1]. If balloon 5 is last, its gain is 151 = 5, and the left sub-interval (0, 2) contains balloon 1 with walls 1 and 5, gain 115 = 5, for a total of 10. If balloon 1 is last, its gain is 111 = 1, and the right sub-interval contains 5 with walls 1 and 1, gain 5, for a total of 6. The answer is 10, with balloon 5 burst last (so balloon 1 is burst first).
Exercise
You must cut a stick of length L at given positions. Each cut costs the current length of the piece being cut. Should dp[i][j] over the sorted cut positions choose the first cut or the last cut in the range, and why?
Show answer
The first cut. A cut separates the piece into two parts that never affect each other again, and its cost (the length between the two enclosing positions) is fixed by the state. So dp[i][j] = (pos[j] - pos[i]) + min over i < k < j of dp[i][k] + dp[k][j], using exclusive bounds that include 0 and L as walls. Reading time backwards turns it into a merging problem, so both framings give the same recurrence. Burst balloons has no such separation, which is why it needs the last-operation view.
Exercise
In max_coins, why do both recursive calls include k (best(left, k) and best(k, right)) instead of excluding it as matrix chain does?
Show answer
Under exclusive bounds, k is not a member of either sub-interval. It is the right wall of (left, k) and the left wall of (k, right). It stays unburst while both sides are processed, and that is what makes them independent. The sub-intervals themselves contain only the balloons strictly between their walls.