Multiplying matrices is associative: (AB)C gives the same result as A(BC). But the amount of work can be wildly different. For some chains, one order is hundreds of times faster than another. Matrix chain multiplication finds the cheapest order using interval dynamic programming, where the answer for a range is built from answers for smaller ranges. The same pattern solves many other problems about splitting a sequence.
In this lesson you will learn
- How much it costs to multiply two matrices
- Why the order of multiplication matters
- How many ways there are to place the brackets
- The interval DP recurrence and the order to fill the table
- How to print the best bracketing
You should know dynamic programming in C and recursion.
Why the Order Matters
Multiplying a p × q matrix by a q × r matrix takes p × q × r scalar multiplications and gives a p × r matrix. Take three matrices: A1 is 10 × 30, A2 is 30 × 5 and A3 is 5 × 60.
#include <stdio.h>
/* Compare the cost of every bracketing of A1 A2 A3 (sizes 10x30, 30x5, 5x60) */
int main(void) {
int p = 10, q = 30, r = 5, s = 60;
int left = p * q * r + p * r * s; /* (A1 A2) A3 */
int right = q * r * s + p * q * s; /* A1 (A2 A3) */
printf("(A1 x A2) x A3: %d + %d = %d\n", p * q * r, p * r * s, left);
printf("A1 x (A2 x A3): %d + %d = %d\n", q * r * s, p * q * s, right);
printf("The first order is %.0f times cheaper.\n", (double)right / left);
/* Number of ways to bracket a chain of n matrices (Catalan numbers) */
long ways[16] = {0};
ways[1] = 1;
for (int n = 2; n <= 15; n++)
for (int k = 1; k < n; k++) ways[n] += ways[k] * ways[n - k];
printf("\nBracketings for n matrices:\n");
for (int n = 1; n <= 15; n += 2) printf(" n = %2d: %ld\n", n, ways[n]);
return 0;
}
Output
(A1 x A2) x A3: 1500 + 3000 = 4500
A1 x (A2 x A3): 9000 + 18000 = 27000
The first order is 6 times cheaper.
Bracketings for n matrices:
n = 1: 1
n = 3: 2
n = 5: 14
n = 7: 132
n = 9: 1430
n = 11: 16796
n = 13: 208012
n = 15: 2674440
- Multiplying A1 and A2 first gives a small 10 × 5 matrix, so the second step is cheap. Starting with A2 × A3 creates a large 30 × 60 matrix, which is expensive to use.
- The number of ways to bracket n matrices grows like the Catalan numbers. With 15 matrices there are over 2.6 million orders, so trying them all is not practical.
The Interval DP
Let matrix Ai have size d[i−1] × d[i]. Let dp[i][j] be the cheapest cost to multiply Ai through Aj.
- A single matrix needs no work: dp[i][i] = 0.
- For a longer chain, the last multiplication splits it at some k into (Ai…Ak) × (Ak+1…Aj). Its cost is the cost of each part plus d[i−1] × d[k] × d[j].
- Try every k and keep the smallest.
dp[i][j] = min over i ≤ k < j of dp[i][k] + dp[k+1][j] + d[i−1]·d[k]·d[j]
Each range needs answers for shorter ranges, so we fill the table by chain length: all ranges of length 2, then 3, and so on.
#include <stdio.h>
#include <limits.h>
#define N 5
/* Matrix A_i has size d[i-1] x d[i]. Find the cheapest way to multiply A1..A4. */
static int dp[N][N], split[N][N];
static void print_order(int i, int j) {
if (i == j) { printf("A%d", i); return; }
printf("(");
print_order(i, split[i][j]);
printf(" x ");
print_order(split[i][j] + 1, j);
printf(")");
}
int main(void) {
int d[] = {10, 30, 5, 60, 10}; /* A1: 10x30, A2: 30x5, A3: 5x60, A4: 60x10 */
int n = 4;
for (int i = 1; i <= n; i++) dp[i][i] = 0;
for (int len = 2; len <= n; len++) { /* chain length */
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++) { /* last multiplication splits at k */
int cost = dp[i][k] + dp[k + 1][j] + d[i - 1] * d[k] * d[j];
if (cost < dp[i][j]) { dp[i][j] = cost; split[i][j] = k; }
}
}
}
printf("Cost table (scalar multiplications):\n ");
for (int j = 1; j <= n; j++) printf("%7s%d", "A", j);
printf("\n");
for (int i = 1; i <= n; i++) {
printf(" A%d ", i);
for (int j = 1; j <= n; j++) {
if (j < i) printf("%8s", "-");
else printf("%8d", dp[i][j]);
}
printf("\n");
}
printf("Minimum cost: %d\nBest order: ", dp[1][n]);
print_order(1, n);
printf("\n");
return 0;
}
Output
Cost table (scalar multiplications):
A1 A2 A3 A4
A1 0 1500 4500 5000
A2 - 0 9000 4500
A3 - - 0 3000
A4 - - - 0
Minimum cost: 5000
Best order: ((A1 x A2) x (A3 x A4))
- The top-right cell, dp[1][4] = 5000, is the answer for the whole chain.
split[i][j]remembers the best k.print_orderfollows these splits recursively to rebuild the brackets.- The best order multiplies A1 × A2 (a 10 × 5 result) and A3 × A4 (a 5 × 10 result) separately, then multiplies the two small results: 1500 + 3000 + 500 = 5000.
- There are O(n2) cells and each tries O(n) splits, so the algorithm runs in O(n3) time and O(n2) space.
The Interval DP Pattern
Whenever a problem asks for the best way to split or combine a sequence, and each choice divides a range into two smaller ranges, try interval DP.
| Problem | dp[i][j] means |
|---|---|
| Matrix chain multiplication | Cheapest cost to multiply matrices i..j |
| Optimal binary search tree | Lowest search cost for keys i..j |
| Burst balloons | Most coins from balloons i..j |
| Longest palindromic subsequence | Longest palindrome inside s[i..j] |
| Minimum cost to cut a stick | Cheapest way to make all cuts between i and j |
Common Mistakes
- Filling rows top to bottom instead of by length, so the smaller ranges are not ready yet.
- Using d[i] instead of d[i−1] for the row count of Ai.
- Letting k reach j, which makes the right part empty.
- Thinking the DP multiplies matrices. It only finds the order; the real multiplication comes afterwards.
Practice Exercises
Exercise 1. For sizes d = {5, 10, 3, 12}, find the cheapest way to multiply A1 A2 A3.
Show answer
(A1 A2) A3 costs 5·10·3 + 5·3·12 = 150 + 180 = 330. A1 (A2 A3) costs 10·3·12 + 5·10·12 = 360 + 600 = 960. So (A1 A2) A3 is best, at 330.
Exercise 2. Write the recurrence for the longest palindromic subsequence of s[i..j].
Show answer
If s[i] == s[j], dp[i][j] = dp[i+1][j−1] + 2. Otherwise dp[i][j] = max(dp[i+1][j], dp[i][j−1]). Single characters have dp[i][i] = 1.
Frequently Asked Questions
Is there a faster algorithm than O(n³)?
Yes. The Hu–Shing algorithm solves matrix chain ordering in O(n log n), but it is much more complicated. The O(n3) DP is the standard method for exams and contests.
Where is this used in practice?
Numerical libraries and database query planners choose the order of large multiplications or joins in a similar way, because a good order can save huge amounts of time.
Summary
- Multiplying p × q by q × r costs p·q·r, so the bracketing changes the total cost.
- dp[i][j] = min over k of dp[i][k] + dp[k+1][j] + d[i−1]·d[k]·d[j].
- Fill the table by increasing chain length; store the split to rebuild the order.
- The algorithm is O(n3) time and O(n2) space.
