Matrix Chain Multiplication
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
2 ≤ p.length ≤ 8 (a chain of p.length - 1 matrices) - ◆
1 ≤ p[i] ≤ 100
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteFor a chain of matrices from position i to j, the last multiplication performed is always some split point k: everything from i to k becomes one matrix, everything from k+1 to j becomes another, and those two get multiplied together at the end. Trying every possible k and taking the cheapest one is correct, but two different splits can ask for the cost of the exact same sub-chain — e.g. matrices 2 through 4 might get re-solved once as part of a split at k=1 and again as part of a split at k=3 — and without remembering the answer, each of those re-derives it from scratch.
O(2ⁿ)O(n)1class Solution {
2 public int matrixChainOrder(int[] p) {
3 int n = p.length - 1;
4 if (n <= 1) return 0;
5 return solve(1, n, p);
6 }
7
8 private int solve(int i, int j, int[] p) {
9 if (i == j) return 0;
10 int min = Integer.MAX_VALUE;
11 for (int k = i; k < j; k++) {
12 int cost = solve(i, k, p) + solve(k + 1, j, p) + p[i - 1] * p[k] * p[j];
13 if (cost < min) min = cost;
14 }
15 return min;
16 }
17}Optimal — Bottom-Up Interval DP
OptimalBuild the answer for every sub-chain from the shortest up to the full chain. dp[i][j] holds the minimum cost to multiply matrices i through j. A chain of length 1 (a single matrix) always costs 0. For longer chains, try every split point k between i and j: the cost is dp[i][k] (already known — it's shorter) plus dp[k+1][j] (also already known) plus the cost of multiplying the two resulting matrices together, p[i-1]×p[k]×p[j]. Filling shorter chains first guarantees every dp[i][k] and dp[k+1][j] a longer chain depends on is already sitting there ready to use.
O(n³)O(n²)1class Solution {
2 public int matrixChainOrder(int[] p) {
3 int n = p.length - 1;
4 if (n <= 1) return 0;
5 int[][] dp = new int[n + 1][n + 1];
6 for (int len = 2; len <= n; len++) {
7 for (int i = 1; i <= n - len + 1; i++) {
8 int j = i + len - 1;
9 dp[i][j] = Integer.MAX_VALUE;
10 for (int k = i; k < j; k++) {
11 int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j];
12 if (cost < dp[i][j]) dp[i][j] = cost;
13 }
14 }
15 }
16 return dp[1][n];
17 }
18}