Dynamic Programming · Pattern 9 of 12
Interval DP: solve every range, short to long
dp[i][j] is the answer for the range i..j. Try every split point k inside it and combine the two sides. Fill by range length so the smaller ranges are ready.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- The cost depends on the order you merge, multiply or remove things
- Two players take from either end of an array
- Brackets or the last operation split the range into a left and a right part
The template
// Matrix Chain: matrix i is arr[i - 1] x arr[i]; dp[i][j] = cheapest way to multiply i..j
int matrixMultiplication(int[] arr) {
int n = arr.length;
int[][] dp = new int[n][n]; // one matrix alone costs 0
for (int len = 2; len < n; len++) // number of matrices, short ranges first
for (int i = 1; i + len - 1 < n; i++) {
int j = i + len - 1;
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++) // the last multiplication is (i..k) x (k+1..j)
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j]);
}
return dp[1][n - 1];
}
// Burst Balloons: choose the LAST balloon k burst between l and r (both kept as walls)
int maxCoins(int[] nums) {
int n = nums.length + 2;
int[] a = new int[n];
a[0] = a[n - 1] = 1; // pad with 1s
for (int i = 0; i < nums.length; i++) a[i + 1] = nums[i];
int[][] dp = new int[n][n]; // dp[l][r] = best coins for the balloons strictly between
for (int len = 2; len < n; len++)
for (int l = 0; l + len < n; l++) {
int r = l + len;
for (int k = l + 1; k < r; k++)
dp[l][r] = Math.max(dp[l][r], dp[l][k] + dp[k][r] + a[l] * a[k] * a[r]);
}
return dp[0][n - 1];
} def matrix_multiplication(arr):
n = len(arr) # matrix i is arr[i - 1] x arr[i]
dp = [[0] * n for _ in range(n)] # one matrix alone costs 0
for length in range(2, n): # number of matrices, short ranges first
for i in range(1, n - length + 1):
j = i + length - 1
dp[i][j] = min(dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j]
for k in range(i, j)) # the last multiplication splits at k
return dp[1][n - 1]
def max_coins(nums):
a = [1] + nums + [1] # pad with 1s
n = len(a)
dp = [[0] * n for _ in range(n)] # dp[l][r] = best coins for the balloons strictly between
for length in range(2, n):
for l in range(n - length):
r = l + length
for k in range(l + 1, r): # k is the LAST balloon burst between l and r
dp[l][r] = max(dp[l][r], dp[l][k] + dp[k][r] + a[l] * a[k] * a[r])
return dp[0][n - 1] // Matrix Chain: matrix i is arr[i - 1] x arr[i]; dp[i][j] = cheapest way to multiply i..j
int matrixMultiplication(vector<int>& arr) {
int n = arr.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int len = 2; len < n; len++) // number of matrices, short ranges first
for (int i = 1; i + len - 1 < n; i++) {
int j = i + len - 1;
dp[i][j] = INT_MAX;
for (int k = i; k < j; k++) // the last multiplication is (i..k) x (k+1..j)
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j]);
}
return dp[1][n - 1];
}
// Burst Balloons: choose the LAST balloon k burst between l and r
int maxCoins(vector<int>& nums) {
vector<int> a = {1};
a.insert(a.end(), nums.begin(), nums.end());
a.push_back(1); // pad with 1s
int n = a.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int len = 2; len < n; len++)
for (int l = 0; l + len < n; l++) {
int r = l + len;
for (int k = l + 1; k < r; k++)
dp[l][r] = max(dp[l][r], dp[l][k] + dp[k][r] + a[l] * a[k] * a[r]);
}
return dp[0][n - 1];
} // Matrix Chain: matrix i is arr[i - 1] x arr[i]; dp[i][j] = cheapest way to multiply i..j
function matrixMultiplication(arr) {
const n = arr.length;
const dp = Array.from({ length: n }, () => new Array(n).fill(0));
for (let len = 2; len < n; len++) // number of matrices, short ranges first
for (let i = 1; i + len - 1 < n; i++) {
const j = i + len - 1;
dp[i][j] = Infinity;
for (let k = i; k < j; k++) // the last multiplication is (i..k) x (k+1..j)
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j]);
}
return dp[1][n - 1];
}
// Burst Balloons: choose the LAST balloon k burst between l and r
function maxCoins(nums) {
const a = [1, ...nums, 1], n = a.length; // pad with 1s
const dp = Array.from({ length: n }, () => new Array(n).fill(0));
for (let len = 2; len < n; len++)
for (let l = 0; l + len < n; l++) {
const r = l + len;
for (let k = l + 1; k < r; k++)
dp[l][r] = Math.max(dp[l][r], dp[l][k] + dp[k][r] + a[l] * a[k] * a[r]);
}
return dp[0][n - 1];
} The variations
-
1Split the range at k
The last operation splits
i..jintoi..kandk + 1..j; try everyk. Matrix Chain adds the cost of the final product. The Score of Students computes the set of all values every sub-expression can take, and Strange Printer merges a character with a later equal one.Now you solve -
2The last item removed
When removing an item changes its neighbours, think backwards: pick the item removed last in the range. Its neighbours at that moment are the range borders, which never change.
Now you solve -
3Two players on a range
Players take from either end.
dp[i][j]= how much more the player to move can score than the other ona[i..j]. Player 1 wins ifdp[0][n - 1] >= 0.
Mistakes to avoid
- Looping
iandjfrom 0 upwards:dp[i][j]then reads ranges that are not filled yet. Loop over the length first. - Burst Balloons: choosing the first balloon to burst makes the neighbours change; choose the last one, whose neighbours are the fixed walls
landr. - Predict the Winner: storing each player's score separately. Store the score difference for the player to move:
max(a[i] - dp[i + 1][j], a[j] - dp[i][j - 1]).
Lesson done
Next: Tree DP: answers from the children up →Mark it done once you can write the template from memory and you have solved the worked examples yourself.