oneby7

2-D Dynamic Programming Splitting a range

574. Matrix Chain Multiplication

Hard

You are given n matrices to multiply in a row, described by one array dims of n + 1 numbers. Matrix m, counting from 0, has dims[m] rows and dims[m + 1] columns. So each matrix has as many columns as the next one has rows, and the whole chain can be multiplied.

Multiplying a p × q matrix by a q × r matrix takes p · q · r multiplications of numbers and gives a p × r matrix. To multiply the chain, you multiply two neighbouring matrices at a time until one matrix is left, and you choose the order. The matrices keep their places in the row. Every order gives the same final matrix, but the number of multiplications can differ a lot.

Return the fewest multiplications of numbers needed to multiply the whole chain. A single matrix needs none.

Example 1

Input: dims = [5, 20, 2, 8, 4]

Output: 304

Explanation: The matrices are 5 × 20, 20 × 2, 2 × 8 and 8 × 4. Multiply the first two for 5 · 20 · 2 = 200 and the last two for 2 · 8 · 4 = 64. That leaves a 5 × 2 and a 2 × 4 matrix, which take 5 · 2 · 4 = 40 more, so 304 in all.

Example 2

Input: dims = [7, 3]

Output: 0

Explanation: There is one 7 × 3 matrix, so there is nothing to multiply.

Example 3

Input: dims = [10000, 10000, 10000, 10000]

Output: 2000000000000

Explanation: Both orders multiply two 10000 × 10000 matrices twice, and each of those takes 1012 multiplications.

Check your understanding

Work out the answer for this input before you write any code.

dims = [6, 2, 9, 3, 7]

Constraints

  • 2 ≤ dims.length ≤ 300
  • 1 ≤ dims[i] ≤ 104

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.