 2

# Matrix Chain Multiplication

Difficulty: EASY Contributed By
Nishant Chitkara

Problem Statement
Suggest Edit

#### You are given ‘N’ 2-D matrices and an array/list “ARR” of length ‘N + 1’ where the first ‘N’ integers denote the number of rows in the Matrices and the last element denotes the number of columns of the last matrix. For each matrix, the number of columns is equal to the number of rows of the next matrix. You are supposed to find the minimum number of multiplication operations that need to be performed to multiply all the given matrices.

##### Note :
``````You don’t have to multiply the matrices, you only have to find the minimum number of multiplication operations.
``````
##### For Example :
``````ARR = {2, 4, 3, 2}

Here, we have three matrices with dimensions {2X4, 4X3, 3X2} which can be multiplied in the following ways:
a. If the order of multiplication is (2X4, 4X3)(3X2), then the total number of multiplication operations that need to be performed are: (2*4*3) + (2*3*2) = 36

b. If the order of multiplication is (2X4)(4X3, 3X2), then the total number of multiplication operations that need to be performed are  (2*4*2) + (4*3*2) = 40
``````
##### Input Format :
``````The first line contains a single integer ‘T’ denoting the number of test cases. The test cases are as follows.

The first line of each test case contains a single integer ‘N’ denoting the number of the matrices.

The second line of each test case contains ‘N + 1’ single space-separated integers denoting where the first ‘N’ integers denote the number of rows in the Matrices and the last element denotes the number of columns of the last matrix.
``````
##### Output Format :
``````For each test case, print the minimum number of multiplication operations that need to be performed to multiply all the given matrices.

Print the output of each test case on a new line.
``````
##### Note :
``````You don’t need to print anything; It has already been taken care of.
``````
##### Constraints :
``````1 <= T <= 5
1 <= N <= 100
1 <= ARR[i] <= 10^2

Time Limit: 1 sec
``````
##### Sample Input 1 :
``````2
4
2 4 3 2
5
1 2 4 1 3
``````
##### Sample Output 1 :
``````36
13
``````
##### Explanation For Sample Input 1 :
``````In the first test case, the minimum operations can be obtained by multiplying the matrices in the following order (2X4, 4X3)(3X2).

In the second test case, the minimum operations can be obtained by multiplying the matrices in the following order (1X2, (2X4, 4X1)),(1X3).
``````
##### Sample Input 2 :
``````2
4
2 3 2 3
3
3 4 5
``````
##### Sample Output 2 :
``````24
60
``````   Console