Matrix Chain Multiplication

Moderate
0/80
Average time to solve is 40m
profile
Contributed by
152 upvotes
Asked in companies
WalmartInfo Edge India (Naukri.com)Morgan Stanley

Problem statement

Given a chain of matrices A1, A2, A3,.....An. Your task is to find out the minimum cost to multiply these matrices. The cost of matrix multiplication is defined as the number of scalar multiplications. A Chain of matrices A1, A2, A3,.....An is represented by a sequence of numbers in an array ‘arr’ where the dimension of 1st matrix is equal to arr[0] * arr[1] , 2nd matrix is arr[1] * arr[2], and so on.

For example:

For arr[ ] = { 10, 20, 30, 40}, matrix A1 = [10 * 20], A2 = [20 * 30], A3 = [30 * 40]

Scalar multiplication of matrix with dimension 10 * 20 is equal to 200.
Detailed explanation ( Input/output format, Notes, Images )

Input Format:

The first line of input contains an integer ‘T’, denoting the number of test cases. Then each test case follows.

The first line of each test case contains the Integer ‘N’ denoting the number of elements in the array.

The second and the last line of each test case contains ‘N’ single space-separated integers representing the elements of the array.

Output Format:

For each test case, print a single integer, denoting the minimum cost of matrix multiplication.

Output of each test case will be printed on a separate line.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.

Constraints:

1 <= T <= 5
2 <= N <= 100
1 <= arr[i] <= 400 

Time Limit: 1 sec.

Sample Input 1:

2
4
4 5 3 2
4
10 15 20 25

Sample Output 1:

70
8000

Sample Output Explanation 1:

In the first test case, there are three matrices of dimensions A = [4 5], B = [5 3] and C = [3 2]. The most efficient order of multiplication is A * ( B * C).
Cost of ( B * C ) = 5 * 3 * 2 = 30  and (B * C) = [5 2] and A * (B * C) = [ 4 5] * [5 2] = 4 * 5 * 2 = 40. So the overall cost is equal to 30 + 40 =70.

In the second test case, there are two ways to multiply the chain - A1*(A2*A3) or (A1*A2)*A3.

If we multiply in order- A1*(A2*A3), then the number of multiplications required is 11250.

If we multiply in order- (A1*A2)*A3, then the number of multiplications required is 8000.

Thus a minimum number of multiplications required is 8000. 

Sample Input 2:

1
4
1 4 3 2

Sample Output 2:

18

Explanation of Sample Output 2:

In the first test case, there are three matrices of dimensions A = [1 4], B = [4 3] and C = [3 2]. The most efficient order of multiplication is (A *  B) * C .
Hint

Try out all possible combinations and avoid recomputation of repetitive subproblems.

Approaches (2)
Recursive with memoization (bottom up )

The idea is to try out all possible combinations of parentheses from left to right and avoid the computation of repetitive subproblems with memoization.

  • place parentheses at all possible places,
  • calculate the cost for each placement and return the minimum value.
  • In a chain of matrices of size ‘ n’, we can place the first set of parentheses in ‘n’ - 1 way.

 

Minimum number of multiplication needed to multiply a chain of size n = Minimum of all ‘n ‘-1 placements (these placements create subproblems of smaller size)

 

Therefore, the problem has optimal substructure property and can be easily solved using recursion.

Also, there is a lot of repetition in subproblems hence do memoization.

 

Algorithm :

 

Take ‘dp[102][102]’ a global 2D matrix, for memoization.

 

Let matrixMultiplication(arr, N) be the function, returns the minimum cost of matrix multiplication.

  • Initialize ‘dp’ with -1.
  • Make a helper function ‘calculateCost’ that takes three parameters (arr, 1, N - 1).
  • Call the ‘calculateCost’ function and store the return answer in the ‘ans’ variable.
  • Return ‘ans’

 

Description of ‘calculateCost’ function:

 

It takes three parameters (arr, i, j) and returns the minimum cost of matrix multiplication of matrices that end ‘i’ to ‘j’ index in the array.

 

  • If ’i’ is greater than or equal to ‘j’
    • Return 0
  • If ‘dp[i][j] is not equal to -1
    • Return ‘dp[i][j]’
  • Take a variable ‘ans’ and initialize it with infinity (INT_MAX)
  • Run a loop from ‘i’ to ‘j’ - 1
    • Take a variable ‘temp’ and store the temporary answer i.e calculateCost(arr, i, k) + calculateCost(arr, k + 1, j) + (arr[k] * arr[i - 1] * arr[j])
    • If temporary answer ‘temp’ is smaller than ‘ans’, then update ‘ans’ with ‘temp’
  • Store ‘ans’ at ‘dp[i][j]’
  • Return ‘ans’
Time Complexity

O(N ^ 3)   where ‘N’ is the number of elements in a given array.

 

In the worst case, we have to solve (N * N) subproblems and each problem takes O(N), Hence the overall time complexity is O( N * N * N) = O(N ^ 3).

Space Complexity

 O(N ^ 2), where N is the number of elements in the given array. 

 

We are using a 2D array ‘dp’ for memoization. Hence space complexity is O( N ^ 2). It also uses a system stack.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Matrix Chain Multiplication
Full screen
Console