2-D Dynamic Programming Splitting a range
574. Matrix Chain Multiplication
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]
304Explanation: 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]
0Explanation: There is one 7 × 3 matrix, so there is nothing to multiply.
Example 3
Input: dims = [10000, 10000, 10000, 10000]
2000000000000Explanation: 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.
Constraints
2 ≤ dims.length ≤ 3001 ≤ dims[i] ≤ 104
Clarifying questions
What you would ask an interviewer before writing any code.