KatInterview

Find Minimum Cost to Multiply a Chain of Matrices

Dynamic ProgrammingAuto-graded · 21 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingoptimizationrecursion

Last 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)C costs 10·30·5 + 10·5·60 = 1500 + 3000 = 4500 operations
  • A(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 matrix i (1-indexed) has dimensions dims[i-1] × dims[i]
  • The list has length n+1 where n is the number of matrices

Output: A list containing exactly two elements:

  1. An integer: the minimum number of scalar multiplications required
  2. 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.