Find Minimum Cost to Multiply a Chain of Matrices
Dynamic ProgrammingAuto-graded · 21 test casesLast updated
Tests dynamic programming on interval optimization, optimal substructure, and avoiding greedy pitfalls in matrix multiplication ordering.
You are given a sequence of matrices to multiply together. Each matrix is represented by its dimensions: matrix i has dimensions dims[i-1] × dims[i].
Multiplying two matrices of dimensions p × q and q × r requires p * q * r scalar multiplications and produces a matrix of dimensions p × r.
Matrix multiplication is associative, meaning different parenthesizations produce the same result but require different numbers of operations. For example, if you have three matrices A (10×30), B (30×5), and C (5×60):
(AB)Ccosts 10·30·5 + 10·5·60 = 1500 + 3000 = 4500 operationsA(BC)costs 30·5·60 + 10·30·60 = 9000 + 18000 = 27000 operations
Your task is to determine the minimum number of scalar multiplications needed to compute the product of all matrices, and return the optimal parenthesization.
Input:
dims: a list of integers where matrixi(1-indexed) has dimensionsdims[i-1] × dims[i]- The list has length
n+1wherenis the number of matrices
Output: A list containing exactly two elements:
- An integer: the minimum number of scalar multiplications required
- A string: the optimal parenthesization using format
"A1","A2", etc. for matrices and parentheses to show grouping (e.g.,"((A1A2)A3)")
If there are fewer than 1 matrix (dims length ≤ 1), return [0, ""].
Constraints
- 0 ≤ len(dims) ≤ 100
- 1 ≤ dims[i] ≤ 1000
- All dimensions are positive integers
Examples
Example 1
Input: min_matrix_chain_cost([10, 30, 5, 60, 2, 100])
Output: [3500, '((A1(A2(A3A4)))A5)']
Hints
Hint 1
Build a table where entry [i,j] represents the minimum cost to multiply matrices i through j. Fill it by considering all possible positions to place the final multiplication.
Hint 2
For each subchain, try every possible split point k and pick the one that minimizes: cost(left part) + cost(right part) + cost(combining the two results).
Hint 3
Process subchains in increasing order of length so that smaller subproblems are solved before they're needed by larger ones.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a classic interval dynamic programming problem. The key insight is that any parenthesization of matrices Ai through Aj must have a final multiplication that splits the chain at some position k, computing (Ai...Ak) and (Ak+1...Aj) separately, then multiplying those two results together.
We build a table where dp[i][j] stores the minimum cost to multiply matrices i through j. For each interval, we try every possible split point and choose the one that minimizes the total cost.
The recurrence relation is:
- Base case:
dp[i][i] = 0(single matrix needs no multiplication) - Recursive case:
dp[i][j] = min over all k in [i, j) of: dp[i][k] + dp[k+1][j] + dims[i] * dims[k+1] * dims[j+1]
The third term represents the cost of multiplying the two resulting subchains: the left result has dimensions dims[i] × dims[k+1] and the right has dims[k+1] × dims[j+1].
We track the optimal split point for each interval in a separate table, then use it to recursively reconstruct the parenthesization string.
Why it works: The problem exhibits optimal substructure. If the optimal way to compute Ai...Aj splits at position k, then the left and right parts must themselves be computed optimally. If either subchain could be computed more cheaply, we could improve the overall solution, contradicting optimality.
Why greedy fails: A greedy approach that always chooses the locally cheapest multiplication doesn't work because the cost of a multiplication depends on the shapes of its operands, which depend on previous choices. Early choices affect all subsequent dimensions, so local optimization misses global structure.
Complexity
- Time: O(n³) where n is the number of matrices. We fill O(n²) table entries, and each requires trying O(n) split points.
- Space: O(n²) for the cost and split tables.
Solution
from typing import List
def min_matrix_chain_cost(dims: List[int]) -> List:
n = len(dims) - 1
if n <= 0:
return [0, ""]
costs = [[0] * n for _ in range(n)]
split = [[-1] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
best = None
for k in range(i, j):
candidate = (costs[i][k] + costs[k + 1][j]
+ dims[i] * dims[k + 1] * dims[j + 1])
if best is None or candidate < best:
best = candidate
split[i][j] = k
costs[i][j] = best
def build(i, j):
if i == j:
return f"A{i + 1}"
k = split[i][j]
return f"({build(i, k)}{build(k + 1, j)})"
return [costs[0][n - 1], build(0, n - 1)]