Matrix Chain Multiplication (MCM) | DP¶
1. Problem Statement¶
Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.
- Twisted version of this problem is given in Leetcode | Minimum score triangulation of Polygon
2. Solution¶
- Time Complexity --> \(O(n^3)\)
- Memoized with DP
int f(vector<int>& arr, int i, int j){
// base condition
if(i == j)
return 0;
int mini = INT_MAX;
// partitioning loop
for(int k = i; k<= j-1; k++){
int ans = f(arr,i,k) + f(arr, k+1,j) + arr[i-1]*arr[k]*arr[j];
mini = min(mini,ans);
}
return mini;
}
int matrixMultiplication(vector<int>& arr, int N){
int i =1;
int j = N-1;
return f(arr,i,j);
}
- Tabulation Method
- For the memoized solution we see that for calculating
f(i, j)
we need to calculatef(i, k)
andf(k+1, j)
for alli <= k < j
. That is forf(i, k)
part, we needf(i, i + 1)
,f(i, i + 2)
, ...,f(i, j - 1)
. We see that all these values lie in rowi
of the memoization table. Similarly, forf(k + 1, j)
part, we needf(i + 1, j)
,f(i + 2, j)
, ...,f(j - 1, j)
. We see that all these values lie in columnj
of the memoization table. - Specifically, all the entries that is below
f(i, j)
but abovef(j, j)
and to left off(i, j)
but just right off(i, i)
are the entries that we need to calculatef(i, j)
. - Thus, we first iterate
i
fromN- 1
to1
so that entries below any row are filled and then iteratej
fromi + 1
toN - 1
so that entries to the left of any column are filled.