What is Matrix Chain Multiplication
Matrix multiplication is associative: (AB)C and A(BC) do different amounts of scalar work. dims lists the shapes. dp[i][j] is the cheapest way to multiply matrices i..j. Try every split k and add the cost of the final multiply.
Brute force approach
k of the chain and recurse on both sides. The number of parenthesizations is Catalan — exponential.A chain from matrix i to matrix j tries every split k. Each split makes two smaller chain calls. The same chain is priced inside different parents. Memoization stores the chain (i, j).
Enter 4 dimensions (3 matrices), for example 10 20 30 40. The classic 40 20 30 10 30 costs 26000 and is the practice case.
Memoized approach
dp[i][j] = min_k dp[i][k] + dp[k+1][j] + dims[i]·dims[k+1]·dims[j+1].Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
10, 20, 30, 40 (three matrices). The cheapest parenthesization costs 18000. Step through the DP table. The live code on the right is the DP recurrence — brute force is shown in Implementations below so you can see why it TLE.Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each split | O(1) |
| All intervals × splits | O(n³) |
| Space | O(n²) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations