Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The cheapest order to multiply matrices

Hard · Target 25 minutes · Dynamic programming

A chain of matrices is described by dims: matrix i has dims[i] rows and dims[i + 1] columns, so there are dims.length − 1 matrices. Multiplying a p × q matrix by a q × r matrix costs p · q · r scalar multiplications. Return the minimum total cost of computing the product of the whole chain, over all ways of placing the brackets.

Examples

InputOutputWhy
dims = [10,30,5,60]4500(A·B)·C: 1,500 + 3,000.
dims = [40,20,30,10,30]26000(A·(B·C))·D.
dims = [10,20]0A single matrix.

Constraints

  • 2 ≤ dims.length ≤ 200
  • 1 ≤ dims[i] ≤ 500

Hints

Hint 1

Some multiplication is done last. It splits the chain i..j into i..k and k + 1..j.

Hint 2

cost(i, j) = min over k of cost(i, k) + cost(k + 1, j) + dims[i] · dims[k + 1] · dims[j + 1].

Hint 3

Intervals read shorter intervals: fill by increasing length.

Where people lose marks

  • Off-by-one between matrix indices and dims indices: matrix k is dims[k] × dims[k + 1].
  • Filling the table row by row from the top, before shorter intervals in later rows exist.
  • Overflow: costs reach about 200 · 500³ = 2.5 · 10¹⁰, beyond 32 bits.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.