Interval DP: bursting balloons and cutting sticks
🌍 In real life. At a fair, a row of balloons carries numbers: 3, 1, 5, 8. Burst one and you win the product of its number and its two current neighbours (a missing neighbour counts as 1). After it bursts, its neighbours become next to each other. In what order should you burst them to win the most? (LeetCode 312.)
A carpenter has the same kind of problem: a 7-metre bamboo must be cut at 1, 3, 4 and 5 metres, and each cut costs the length of the piece being cut. The order changes the total (LeetCode 1547).
In both, choosing one item splits the problem into a left range and a right range. The DP's state is a range [l, r]: interval DP.
The idea in one sentence: dp[l][r] is the best answer for the items strictly between positions l and r; try every item k as the one that splits the range (for balloons: the last one burst, whose neighbours are then l and r), and fill the table from short ranges to long ones.
Its words:
- interval DP: a DP whose state is a range of positions,
dp[l][r] - split point k: the item whose choice divides
(l, r)into(l, k)and(k, r) - last balloon: thinking about the last burst instead of the first makes its neighbours fixed: l and r
- gap
r - l: the table is filled in order of gap, so smaller ranges are always ready
Why the last balloon. If k is burst first, its neighbours are known but the two sides then interact: a balloon on the left may later sit next to one on the right. If k is burst last in (l, r), everything else between l and r is already gone, so its neighbours are exactly l and r, and the left part (l, k) and the right part (k, r) never touch: independent subproblems.
For balloons 3, 1, 5 (with walls of 1 at both ends, positions 0 and 4):
Why it is correct. Every way of bursting the balloons between l and r has a last balloon k. Before k bursts, the balloons in (l, k) and in (k, r) are separated by k, so their orders don't affect each other, and the best for each side is dp[l][k] and dp[k][r]. Trying every k covers every possible order. Filling by gap guarantees both sides are already computed.
Cutting a stick is the same shape. With the cut points sorted and the two ends added, dp[i][j] is the cheapest way to make every cut between points i and j. Whichever cut k is made first costs the whole piece, points[j] - points[i], and leaves two independent pieces. (Here "first" works, because a cut splits the stick for good.)
What it costs, by counting. About n²/2 ranges, each trying up to n split points: O(n³) time and O(n²) memory. For 300 balloons that is 27 million steps, against n! = more than 10⁶¹⁴ orders to try one by one. Other problems with this shape: matrix-chain multiplication, the cheapest way to merge stones, and the palindromes of Lesson 59.3.
def max_coins(nums):
vals = [1] + nums + [1] # walls worth 1 at both ends
n = len(vals)
dp = [[0] * n for _ in range(n)] # dp[l][r]: best for the balloons between l and r
for gap in range(2, n): # shorter ranges first
for l in range(n - gap):
r = l + gap
for k in range(l + 1, r): # k: the LAST balloon burst in (l, r)
coins = vals[l] * vals[k] * vals[r] + dp[l][k] + dp[k][r]
dp[l][r] = max(dp[l][r], coins)
return dp[0][n - 1]
def cut_cost(length, cuts):
points = [0] + sorted(cuts) + [length]
m = len(points)
dp = [[0] * m for _ in range(m)] # dp[i][j]: cheapest way to make every cut between i and j
for gap in range(2, m):
for i in range(m - gap):
j = i + gap
dp[i][j] = min(dp[i][k] + dp[k][j] for k in range(i + 1, j)) + points[j] - points[i]
return dp[0][m - 1]
print(max_coins([3, 1, 5, 8]), max_coins([1, 5]))
print(cut_cost(7, [1, 3, 4, 5]), cut_cost(9, [5, 6, 1, 4, 2]))Mistakes and edge cases.
- Thinking about the first balloon. After bursting k first, the left and right sides become neighbours, so
(l, k)and(k, r)are not independent and the recurrence is wrong. Use the last one. - Filling row by row.
for l in range(n): for r in range(l + 2, n)readsdp[k][r]for k > l before it is computed. Fill by gap (or l from right to left). - Forgetting the walls. Without the 1s at both ends, the first and last balloons have no neighbour to multiply by.
- Unsorted cuts. The stick's pieces depend on the order of the points along it: sort the cuts first.
- Big inputs. n³ grows fast: 1,000 items is a billion steps. Interval DP suits inputs of a few hundred.
Quiz
What does this print?
def max_coins(nums): vals = [1] + nums + [1] # walls worth 1 at both ends n = len(vals) dp = [[0] * n for _ in range(n)] # dp[l][r]: best for the balloons between l and r for gap in range(2, n): # shorter ranges first for l in range(n - gap): r = l + gap for k in range(l + 1, r): # k: the LAST balloon burst in (l, r) coins = vals[l] * vals[k] * vals[r] + dp[l][k] + dp[k][r] dp[l][r] = max(dp[l][r], coins) return dp[0][n - 1] print(max_coins([2, 3]), max_coins([7]))Why does the recurrence pick k as the LAST balloon burst in (l, r)?
- Then its neighbours are exactly l and r, and the two sides never meet
- Because the last balloon is always the biggest
- To make the table smaller
In what order must dp[l][r] be filled?
- By increasing gap r − l, so every smaller range is ready
- Row by row, l from 0 upwards
- Any order works
max_coins([3, 1, 5, 8]) should be 167, but this gives 63. Which line is wrong?
def max_coins(nums): vals = [1] + nums + [1] n = len(vals) dp = [[0] * n for _ in range(n)] for l in range(n): for r in range(l + 2, n): for k in range(l + 1, r): coins = vals[l] * vals[k] * vals[r] + dp[l][k] + dp[k][r] dp[l][r] = max(dp[l][r], coins) return dp[0][n - 1]
Coding tasks
Write
max_coins(nums): the most coins from bursting every balloon, where bursting balloon i paysleft × nums[i] × rightwith its current neighbours (1 beyond the ends).Write
cut_cost(length, cuts): a stick oflengthmust be cut at every point incuts; each cut costs the length of the piece being cut. Return the cheapest total.