Matrix Chain Multiplication
Let's solve the Matrix Chain Multiplication problem using Dynamic Programming.
Statement
You are given a chain of matrices to be multiplied. You have to find the least number of primitive multiplications needed to evaluate the result.
Note: Given two matrices and of dimensions and , the resulting matrix we get is , whose dimensions are . Further, when multiplying these two matrices, the number of primitive multiplications is .
Your algorithm will take dims
as input, a list denoting the dimensions of the matrices to be multiplied. Since the columns of the first matrix and the rows of the second matrix are the same, we have not repeated this information in the list dims
. So the dimensions of the first matrix would be and the second matrix would have dimensions of . Similarly, the dimensions of the third matrix would be , and so on.
In the illustration below, we see that changing the order in which we multiply the three matrices affects the number of primitive multiplications required to compute the final result:
Constraints:
- 3
dims.length
500 - 1
dims[i]
Examples
No. | Input | Output |
1 | [3, 3, 2, 1] | 15 |
2 | [4, 3, 2, 1] | 18 |
3 | [2, 2, 2] | 8 |
4 | [1, 1, 1] | 1 |
Try it yourself
Implement your solution in the following playground.
#include <limits.h>long MinMultiplications(vector<int> dims){// Write Your Code Herereturn 0;}
Note: If you clicked the “Submit” button and the code timed out, this means that your solution needs to be optimized in terms of running time.
Hint: Use dynamic programming and see the magic.
Solution
We will first explore the naive recursive solution to this problem and then see how it can be improved using the Recursive Numbers dynamic programming pattern.
Naive approach
We can easily imagine dims
to be a list of matrices. Then each recursive call tries to find the optimal placement of two parentheses between these matrices. So, let’s say we have the following sequence of matrices: . Each recursive call tries to place two parentheses, so we have the following possibilities:
-
...