Minimum Cost to Multiply a Chain of Matrices
Dynamic ProgrammingAuto-graded · 20 test casesLast updated
Tests interval dynamic programming by finding the least expensive way to parenthesize consecutive matrix multiplications.
You are given an array of integers matrix_dims representing the dimensions of a sequence of matrices. Each consecutive pair defines one matrix: the matrix at position i has dimensions matrix_dims[i] × matrix_dims[i+1].
When you multiply two matrices of dimensions p × q and q × r, the result is a matrix of dimensions p × r, and the operation requires exactly p * q * r scalar multiplications.
Your task is to compute the minimum total number of scalar multiplications required to compute the product of all matrices in the chain. Matrix multiplication is associative, so different orders of parenthesization yield the same final matrix but may have drastically different computational costs.
Return the minimum number of scalar multiplications needed.
Constraints
2 <= len(matrix_dims) <= 5001 <= matrix_dims[i] <= 1000- If there is only one matrix in the chain (i.e.,
len(matrix_dims) == 2), return0since no multiplication is needed.
Examples
Example 1
Input: min_matrix_mult_cost([10, 30, 5, 60])
Output: 4500
Example 2
Input: min_matrix_mult_cost([1, 2, 3])
Output: 6
Hints
Hint 1
Think about where you place the final multiplication operation in an optimal solution—it always splits the chain into two parts.
Hint 2
Use a table where each entry represents the minimum cost for a contiguous subchain, and fill it by increasing subchain length.
Hint 3
For a subchain from index i to j, try every possible position k where you could place the last multiplication, combining the costs of both halves plus the cost of merging them.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that any way of parenthesizing a matrix chain ultimately performs one final multiplication that combines two sub-chains. For matrices indexed from i to j, we must choose some split point k where we first compute the product of matrices i through k, then compute the product of matrices k+1 through j, and finally multiply these two results together.
The resulting matrix from the left sub-chain has dimensions matrix_dims[i] × matrix_dims[k+1], and the right sub-chain produces matrix_dims[k+1] × matrix_dims[j+1]. Multiplying these two intermediate results costs matrix_dims[i] * matrix_dims[k+1] * matrix_dims[j+1] scalar operations.
We use interval dynamic programming: define dp[i][j] as the minimum cost to multiply matrices i through j (inclusive). The recurrence is:
dp[i][i] = 0 (single matrix, no multiplication needed)
dp[i][j] = min over all k in [i, j-1] of:
dp[i][k] + dp[k+1][j] + matrix_dims[i] * matrix_dims[k+1] * matrix_dims[j+1]
We fill the table by increasing sub-chain length, ensuring that when computing dp[i][j], all shorter intervals have already been computed. The final answer is dp[0][n-1] where n is the number of matrices.
Why It Works
The problem exhibits optimal substructure: if an optimal parenthesization splits at position k, then both the left and right sub-chains must themselves be optimally parenthesized. Otherwise, we could substitute a better solution for one of the sub-chains and reduce the total cost, contradicting optimality.
By trying every possible final split point and taking the minimum, we guarantee finding the optimal solution.
Complexity
Time Complexity: O(n³) where n is the number of matrices. We have O(n²) intervals to fill, and for each interval we try O(n) possible split points.
Space Complexity: O(n²) for the DP table storing results for all intervals.
Solution Code
from typing import List
def min_matrix_mult_cost(matrix_dims: List[int]) -> int:
num_matrices = len(matrix_dims) - 1
if num_matrices <= 1:
return 0
inf = float("inf")
dp = [[0] * num_matrices for _ in range(num_matrices)]
for chain_len in range(2, num_matrices + 1):
for i in range(num_matrices - chain_len + 1):
j = i + chain_len - 1
min_cost = inf
left_rows = matrix_dims[i]
right_cols = matrix_dims[j + 1]
dp_row = dp[i]
for k in range(i, j):
current_cost = dp_row[k] + dp[k + 1][j] + left_rows * matrix_dims[k + 1] * right_cols
if current_cost < min_cost:
min_cost = current_cost
dp_row[j] = min_cost
return dp[0][num_matrices - 1]