Learn the pattern · ~15 min
Interval DP
also called range DP, matrix-chain style
When a range's best answer depends only on the range itself, try every split point inside it (often: what happens last) and build long ranges out of shorter ones you've already solved.
Reach for it when you read
- +A range's answer depends only on that range, and a move splits it into a left part and a right part.
- +Burst, merge, cut or remove things in the best order, where a move's cost depends on its current neighbours.
- +Triangulate a polygon, or choose where the brackets go in a chain of multiplications.
- +Two players take from either end of a row.
- +n is a few hundred, so n³ fits.
Not this one when
- ×You only ever cut off a prefix and solve the rest (word break, partitions): a 1-D DP over prefixes.
- ×Repeatedly merge any two items, cheapest pair first: greedy with a heap.
- ×Many queries for the sum or min of
[l, r]: prefix sums or a segment tree.
Learn Interval DP
First, what is an interval?
An interval is a run of neighbouring positions in a row, with no gaps. In 4 2 3, the intervals are 4, 2, 3, 4 2, 2 3 and 4 2 3. 4 3 is not one: it skips the 2.
Interval DP answers a question for every interval and builds a long interval's answer out of shorter ones inside it. Picture fence posts: posts i and j stand at the ends, and the items strictly between them are the interval. Pick an item k between them and it splits the range into (i, k) and (k, j), both shorter.
Filling ranges, shortest first
Take posts 0 to 4, with three items between them. The rule:
Solve ranges by length, shortest first. A range only reads shorter ranges, so they are ready.
| range (i, j) | what happens | reads |
|---|---|---|
| (0, 1), (1, 2), (2, 3), (3, 4) | nothing between the posts: the answer is 0 | nothing |
| (0, 2) | one item between, so k = 1 | (0, 1) and (1, 2) |
| (1, 3) | k = 2 | (1, 2) and (2, 3) |
| (2, 4) | k = 3 | (2, 3) and (3, 4) |
| (0, 3) | try k = 1 and k = 2 | (0, 1) + (1, 3), (0, 2) + (2, 3) |
| (1, 4) | try k = 2 and k = 3 | (1, 2) + (2, 4), (1, 3) + (3, 4) |
| (0, 4) | try k = 1, 2 and 3 | (0, 1) + (1, 4), (0, 2) + (2, 4), (0, 3) + (3, 4) |
Every range in the last column appears in an earlier row. That's why we go by length.
The code for it
for (int len = 2; len < n; len++) // shorter ranges first
for (int i = 0; i + len < n; i++) {
int j = i + len;
for (int k = i + 1; k < j; k++) {
// combine (i, k) and (k, j): both are shorter, so both are done
}
}You don't need to memorise this. It's the table above: pick a length, slide the range along the row, and try every split inside it.
Why not loop i from 0 like a normal table? Then (0, 4) is filled before (1, 4), which it needs.
Fine, but how does this help us?
A classic problem: Burst Balloons. Bursting a balloon earns left · it · right, its neighbours at that moment (a missing one counts as 1). Burst them all for the most coins.
For [4, 2, 3] there are only six orders. Try them all:
order coins for each burst total
4, 2, 3 1·4·2 + 1·2·3 + 1·3·1 17
4, 3, 2 1·4·2 + 2·3·1 + 1·2·1 16
2, 4, 3 4·2·3 + 1·4·3 + 1·3·1 39
2, 3, 4 4·2·3 + 4·3·1 + 1·4·1 40
3, 4, 2 2·3·1 + 1·4·2 + 1·2·1 16
3, 2, 4 2·3·1 + 4·2·1 + 1·4·1 18The answer is 40: burst 2 (24), then 3 (12), then 4 (4).
The brute force
The choices: which balloon bursts next. Try each one, then solve what's left.
int brute(vector<int> b) { // the balloons still standing, in order
int best = 0;
for (int p = 0; p < (int)b.size(); p++) {
int left = p > 0 ? b[p - 1] : 1, right = p + 1 < (int)b.size() ? b[p + 1] : 1;
vector<int> rest = b;
rest.erase(rest.begin() + p); // burst balloon p next
best = max(best, left * b[p] * right + brute(rest));
}
return best;
}Draw the top of the calls for [4, 2, 3]:
- brute([4,2,3])
- burst 4 → brute([2,3])
- burst 2 → brute([3])
- burst 3 → brute([2])
- burst 2 → brute([4,3])
- burst 4 → brute([3])← [3] again
- burst 3 → brute([4])
- burst 3 → brute([4,2]) …
That's 16 calls for three balloons, and n! orders in general: about 9.9 million calls for n = 10 (25 s already at n = 12), and a 615-digit number of orders for n = 300. Time limit exceeded.
The one thought: choose the last one
Point at brute([3]). It's reached twice: after "4 then 2" and after "2 then 4". The 3 is left alone either way, so the answer is the same. The state repeats.
But that state is the set of balloons left, and there are 2ⁿ sets. Worse, a set isn't a range: burst the 2 first and what's left, 4 3, skips a position. The 4 and the 3 now touch, so each side's coins depend on the other. Choosing the first balloon doesn't split the problem.
Now choose the last one instead. Pad with walls: a = [1, 4, 2, 3, 1], posts 0 to 4. Say balloon k bursts last between posts i and j. Until then k stands between the two sides, so (i, k) and (k, j) never meet. When k finally bursts, everything else is gone, so its neighbours are exactly a[i] and a[j]. Two independent, shorter ranges:
best(i, j) = max over k of best(i, k) + a[i]·a[k]·a[j] + best(k, j)
The state is now a range, and only about n²/2 ranges exist. That's the interval fill from the top of the page.
Memoise it
int best(int i, int j) { // most coins for the balloons between posts i and j
if (memo[i][j] != -1) return memo[i][j];
int res = 0; // no balloon inside → 0
for (int k = i + 1; k < j; k++) // k bursts last
res = max(res, best(i, k) + a[i] * a[k] * a[j] + best(k, j));
return memo[i][j] = res;
}
// answer: best(0, n - 1)Without the memo, ranges still repeat: (1, 3), just the 2, is asked for by both (0, 3) and (1, 4).
The bottom-up table
vector<int> a = {1}; // walls on both ends
for (int x : nums) a.push_back(x);
a.push_back(1);
int n = a.size();
vector<vector<int>> dp(n, vector<int>(n, 0)); // nothing inside → 0
for (int len = 2; len < n; len++)
for (int i = 0; i + len < n; i++) {
int j = i + len;
for (int k = i + 1; k < j; k++) // k bursts last
dp[i][j] = max(dp[i][j], dp[i][k] + a[i] * a[k] * a[j] + dp[k][j]);
}
// answer: dp[0][n - 1]Dry run
Same balloons, a = [1, 4, 2, 3, 1], ranges by length.
| posts (i, j) | balloons inside | what happens | dp[i][j] |
|---|---|---|---|
| (0, 2) | 4 | only the 4: 1·4·2 | 8 |
| (1, 3) | 2 | only the 2: 4·2·3 | 24 |
| (2, 4) | 3 | only the 3: 2·3·1 | 6 |
| (0, 3) | 4, 2 | 4 last: 0 + 1·4·3 + 24 = 36; 2 last: 8 + 1·2·3 + 0 = 14 | 36 |
| (1, 4) | 2, 3 | 2 last: 0 + 4·2·1 + 6 = 14; 3 last: 24 + 4·3·1 + 0 = 36 | 36 |
| (0, 4) | 4, 2, 3 | 4 last: 0 + 1·4·1 + 36 = 40; 2 last: 16; 3 last: 39 | 40 |
dp[0][4] = 40, the same answer as the brute force.
Why it's O(n³)
Count work per range: about n²/2 ranges, each trying at most n split points. So O(n³) time: for n = 300, about 4.5 × 10⁶ triples (i, k, j). The table is O(n²) space.
From n! orders down to n³, by choosing the last move so that each range is its own problem.
Triangulate a polygon? k is the third corner
Minimum Score Triangulation: cut a polygon into triangles, each scoring the product of its corners. Edge (i, j) is in exactly one triangle; its third corner k splits the rest:
dp[i][j] = min(dp[i][j], dp[i][k] + v[i] * v[k] * v[j] + dp[k][j]);Start dp[i][j] at a big number instead of 0. For corners [1, 3, 2, 4] the answer is 14.
Take from either end? No split at all
Stone Game: two players take a pile from either end. dp[i][j] = how far ahead the player to move can finish on piles i..j. Take one end; the other player then gets ahead by their own dp on what's left:
dp[i][j] = max(p[i] - dp[i + 1][j], p[j] - dp[i][j - 1]);With dp[i][i] = p[i] and i from the right, piles [3, 9, 1, 2] give 7: the first player finishes 7 ahead.
Remember this
- The answer for a range depends only on the range (and its walls) →
dp[i][j], filled by length. - If picking the first move makes the two sides interact, pick the last move instead. Pad with walls.
- Trap: plain
i,jloops read ranges that aren't filled yet. Loop by length, orifrom the right. - Whenever a problem merges, bursts, cuts or takes from the ends of a row and n is a few hundred, it's this table.
Practise it on Minimum Score Triangulation of Polygon, then Guess Number Higher or Lower II (an adversary picks the side), Stone Game (take from the ends), Minimum Cost to Cut a Stick, Burst Balloons and Strange Printer (stretch one move over a range).
Watch it work, line by line
Burst Balloons ↗, nums = [3, 1, 5, 8] → 167 (burst 1, 5, 3, 8: 15 + 120 + 24 + 8). 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
Does the answer for a range depend only on that range and its two ends, and can one choice inside it (a split point, or what happens last) cut it into two independent smaller ranges?
Reach for it when
- +merge/remove/burst things where order matters inside a range
- +two players take from ends
- +cost of cutting/merging segments
- +n up to ~500 for O(n3); ~5000 for O(n2)
It fails when
- ×n in the thousands, so O(n³) is too slowuse Knuth optimisation or a different model
- ×The pieces aren't contiguous segmentsuse A different DP state
Looks like it, isn't (and the other way round)
- Split Array Largest Sum looks like Interval DP, needs Binary Search on the Answer
DP over partitions works (O(k n2)), but 'minimise the largest' points to binary search with greedy check.
- Stone Game looks like Interval DP, needs Combinatorial Game Theory (minimax, Nim, Sprague-Grundy)
Interval DP works, but with an even number of piles the first player can always take all odd or all even indices.
- Minimum Number of Taps to Open to Water a Garden looks like Interval DP, needs Greedy
Convert each tap to its reach interval; the jump-game-ii farthest-reach greedy covers [0, n] 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.
1Why does the outer loop go over the range length?Reveal
dp[i][j] reads smaller ranges inside it. Doing all shorter ranges first makes sure they're final.
2In Burst Balloons, why choose the balloon popped last, not first?Reveal
Until the last one pops, it keeps the two sides apart, and its neighbours at that moment are the range's fixed walls. The first one's neighbours keep changing.
3What's the usual cost, and how big can n be?Reveal
O(n³): n² ranges, n splits each. Fine up to n ≈ 500.
Practice ladder
- 1Minimum Score Triangulation of Polygonplain splitMedium
- 2Guess Number Higher or Lower IIadversaryMedium
- 3Stone Gametake from endsMedium
- 4Removal Gametake from endsMedium
- 5Minimum Cost to Cut a Stickcut positionsHard
- 6Rectangle Cuttingtwo dimensionsMedium
- 7Burst Balloonsthe hookHard
- 8Strange Printerstretch a moveHard
Finished Interval DP? Mark it done and Lessgo moves you to the next step.