818. Matrix Chain Cost

Hard7.5 points estimatedArrayDynamic Programming3 hints

A graphics pipeline applies a chain of linear filters, each stored as a rectangular matrix. The chain is described by dims: filter number i (counting from 0) has dims[i] rows and dims[i+1] columns, so neighbouring filters always fit together. Multiplying a p x q matrix by a q x r matrix costs p*q*r scalar multiplications and yields a p x r matrix.

The product is associative, so you may choose the order of the pairwise multiplications freely. Return the smallest possible total number of scalar multiplications needed to reduce the whole chain to a single matrix. If the chain has fewer than two filters (that is, dims has fewer than 3 entries), return 0.

Aim for time O(n^3) and space O(n^2).

Example 1

Input:
dims = [30,12,45,8]
Output:
7200
Explanation:

Three matrices of shapes 30x12, 12x45 and 45x8: joining the last two first costs 12*45*8 + 30*12*8 = 7200, while the other order costs 27000.

Example 2

Input:
dims = [6,20,3,15,9]
Output:
927
Explanation:

Multiply the first two (360), then the last two (405), then join the results (6*3*9 = 162), a total of 927.

Constraints

0 ≤ dims.length ≤ 300

1 ≤ dims[i] ≤ 100

The answer fits in a 32-bit signed integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n^3)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…