KatInterview

Minimum Cost to Multiply a Chain of Matrices

Dynamic ProgrammingAuto-graded · 20 test cases
HardAuto-gradedDynamic Programminginterval-dpoptimizationmemoization

Last 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) <= 500
  • 1 <= matrix_dims[i] <= 1000
  • If there is only one matrix in the chain (i.e., len(matrix_dims) == 2), return 0 since 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.