Interval dynamic programming
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Interval dynamic programming optimizes decisions over contiguous subarrays or ranges [i, j]. Before drawing tables, we look at the brute-force recursion tree to understand why sub-intervals repeat.
Brute Force Recursion and Why It Is Slow
Plain interval recursion solves a range [i, j] by trying every possible split point k between i and j - 1: solve(i, k) + solve(k + 1, j) + splitCost. For a chain of matrices with dimensions p, it looks like this (shown after the code).
int solve(int[] p, int i, int j) { if (i == j) return 0; // one matrix: nothing to multiply int best = Integer.MAX_VALUE; for (int k = i; k < j; k++) { // try every split point int cost = solve(p, i, k) + solve(p, k + 1, j) + p[i - 1] * p[k] * p[j]; best = Math.min(best, cost); } return best;}Why is this slow? At each split point k, the function branches into two smaller ranges, which each branch into further splits. The total number of ways to parenthesize n items is given by the Catalan numbers, which grow exponentially at O(4^n / n^(1.5)). For n = 20 matrices, there are over 1.7 billion parenthesizations!
Yet many different splits evaluate the exact same sub-interval [2, 5]. By storing answers for each subsegment in a table, we avoid recalculating identical ranges.
The Interval Length Iteration Order
Standard dynamic programming often marches linearly through indices from left to right. In interval DP, state dp[i][j] denotes the optimal answer for the contiguous range from index i to j.
Matrix chain by interval length
Step 1 of 6
| Row | A1 | A2 | A3 | A4 |
|---|---|---|---|---|
| A1 | 0 | |||
| A2 | 0 | |||
| A3 | 0 | |||
| A4 | 0 |
Example 1 · Matrix chain by trying every split, brute force: O(2^n) time, O(n) space
public class MatrixChainBruteDemo { static int cost(int[] p, int i, int j) { if (i == j) return 0; // one matrix: nothing to multiply int best = Integer.MAX_VALUE; for (int k = i; k < j; k++) { // try every split point int total = cost(p, i, k) + cost(p, k + 1, j) + p[i - 1] * p[k] * p[j]; best = Math.min(best, total); } return best; }
public static void main(String[] args) { int[] p = {10, 20, 30, 40, 30}; System.out.println("Minimum scalar multiplications: " + cost(p, 1, p.length - 1)); }}Minimum scalar multiplications: 30000
What this code does
- cost(i, j) tries every split k and adds the two sub-chain costs plus the cost of joining them.
- Sub-chains such as (2, 3) are recomputed inside many different splits.
- It prints 30000, the same answer as the table version.
Example 2 · Matrix chain with interval DP, optimal: O(n³) time, O(n²) space
public class MatrixChainDemo { public static int minOperations(int[] p) { int n = p.length - 1; // number of matrices int[][] dp = new int[n + 1][n + 1];
for (int len = 2; len <= n; len++) { for (int i = 1; i <= n - len + 1; i++) { int j = i + len - 1; dp[i][j] = Integer.MAX_VALUE; for (int k = i; k < j; k++) { int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j]; if (cost < dp[i][j]) { dp[i][j] = cost; } } } } return dp[1][n]; }
public static void main(String[] args) { int[] p = {10, 20, 30, 40, 30}; System.out.println("Minimum scalar multiplications: " + minOperations(p)); }}Minimum scalar multiplications: 30000
What this code does
- Allocates a 2D table dp[i][j] holding minimal operations to multiply matrices i through j.
- Iterates interval length from 2 to n, testing all split points k between i and j - 1.
- Computes scalar cost using dimension triplets p[i-1] * p[k] * p[j] in O(n^3) total time.
- Why faster: dp[i][j] is stored once and shorter chains are solved first, so each of the n² ranges tries n splits: O(n³) instead of exponential.
To compute dp[i][j] of length L, both sub-intervals dp[i][k] and dp[k + 1][j] must already be solved. Notice that both sub-intervals have lengths strictly less than L! Therefore, the outer loop must iterate by interval length, starting from len = 2 up to n. The inner loop steps start index i from 1 to n - len + 1, setting j = i + len - 1. This guarantees that all shorter intervals are solved before longer ones.
Burst Balloons and Inverse Splitting
In the Burst Balloons problem, popping a balloon causes its left and right neighbors to touch, tangling the remaining subproblems. If you try plain recursion from first balloon to pop, the subproblems depend on which neighbors survived, making memoization impossible.
Example 3 · Burst balloons by trying every order, brute force: O(n!) time, O(n) space
import java.util.ArrayList;import java.util.List;
public class BalloonBruteDemo { static int best(List<Integer> balloons) { if (balloons.isEmpty()) return 0; int top = 0; for (int i = 0; i < balloons.size(); i++) { // try every balloon as the next one int left = i == 0 ? 1 : balloons.get(i - 1); int right = i == balloons.size() - 1 ? 1 : balloons.get(i + 1); int gain = left * balloons.get(i) * right; List<Integer> rest = new ArrayList<>(balloons); rest.remove(i); top = Math.max(top, gain + best(rest)); } return top; }
public static void main(String[] args) { List<Integer> nums = List.of(3, 1, 5, 8); System.out.println("Max coins bursting balloons: " + best(new ArrayList<>(nums))); }}Max coins bursting balloons: 167
What this code does
- best(list) bursts each balloon in turn, scores left × balloon × right, and recurses on the shorter list.
- The neighbours change after every burst, so this approach has to try all n! orders.
- It prints 167, the same as the interval DP.
Example 4 · Burst balloons with interval DP, optimal: O(n³) time, O(n²) space
public class BurstBalloonsDemo { public static int maxCoins(int[] nums) { int n = nums.length; int[] val = new int[n + 2]; val[0] = 1; val[n + 1] = 1; for (int i = 0; i < n; i++) { val[i + 1] = nums[i]; }
int[][] dp = new int[n + 2][n + 2];
for (int len = 1; len <= n; len++) { for (int i = 1; i <= n - len + 1; i++) { int j = i + len - 1; for (int k = i; k <= j; k++) { int gain = val[i - 1] * val[k] * val[j + 1]; int total = dp[i][k - 1] + dp[k + 1][j] + gain; if (total > dp[i][j]) { dp[i][j] = total; } } } } return dp[1][n]; }
public static void main(String[] args) { int[] nums = {3, 1, 5, 8}; System.out.println("Max coins bursting balloons: " + maxCoins(nums)); }}Max coins bursting balloons: 167
What this code does
- Pads the balloon array with virtual boundaries of value 1 at index 0 and n + 1.
- Chooses balloon k as the last balloon to pop in interval [i, j], ensuring boundary neighbors i - 1 and j + 1 remain present.
- Evaluates sub-intervals of increasing length to accumulate optimal coin sums.
- Why faster: choosing the LAST balloon to burst splits the problem into two independent ranges, so n! orders become n² ranges.
The breakthrough insight is inverting the decision: pick which balloon k is the LAST one to burst in interval (i, j)! Because all other balloons in (i, j) burst before k, balloon k's immediate neighbors when it finally pops are guaranteed to be boundaries i and j. The transition becomes dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]).
Range Merging and Boundary Padding
Problems like Minimum Cost to Cut a Stick also follow this interval pattern. Making cut k splits a wooden segment into independent left and right pieces.
Example 5 · Minimum cost to cut a stick: O(m³) time, O(m²) space
import java.util.Arrays;
public class CutStickDemo { public static int minCost(int n, int[] cuts) { int m = cuts.length; int[] all = new int[m + 2]; for (int i = 0; i < m; i++) all[i + 1] = cuts[i]; all[0] = 0; all[m + 1] = n; Arrays.sort(all);
int[][] dp = new int[m + 2][m + 2];
for (int len = 2; len <= m + 1; len++) { for (int i = 0; i + len <= m + 1; i++) { int j = i + len; dp[i][j] = Integer.MAX_VALUE; for (int k = i + 1; k < j; k++) { int cost = dp[i][k] + dp[k][j] + (all[j] - all[i]); if (cost < dp[i][j]) { dp[i][j] = cost; } } if (dp[i][j] == Integer.MAX_VALUE) { dp[i][j] = 0; } } } return dp[0][m + 1]; }
public static void main(String[] args) { int[] cuts = {1, 3, 4, 5}; System.out.println("Minimum cost to cut stick: " + minCost(7, cuts)); }}Minimum cost to cut stick: 16
What this code does
- Sorts the cuts and inserts boundary points 0 and stick length n.
- Defines dp[i][j] as the minimum cost to perform all cuts between indices i and j.
- Tests each intermediate cut k, adding segment length all[j] - all[i] to subproblems.
A practical coding technique is padding the cuts array with boundary points 0 and stick length L, and sorting them. The segment length is then directly cuts[j] - cuts[i], and the recurrence tests split points k between i and j in O(n^3) total time.
Order of execution
Order the burst balloons steps
Tap the steps in the order the algorithm runs them.
Next step
Check your understanding
10 quick questions