forked from maheshjainckd/Hacktoberfest2022-for-everyone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrixChainMultiplication.java
45 lines (40 loc) · 1.31 KB
/
MatrixChainMultiplication.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Dynamic Programming Python implementation of Matrix
// Chain Multiplication.
public class MatrixChainMultiplication {
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
static int MatrixChainOrder(int p[], int n) {
/* For simplicity of the program, one extra row and one
extra column are allocated in m[][]. 0th row and 0th
column of m[][] are not used */
int m[][] = new int[n][n];
int i, j, k, L, q;
/* m[i,j] = Minimum number of scalar multiplications needed
to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where
dimension of A[i] is p[i-1] x p[i] */
// cost is zero when multiplying one matrix.
for (i = 1; i < n; i++)
m[i][i] = 0;
// L is chain length.
for (L=2; L<n; L++) {
for (i=1; i<n-L+1; i++) {
j = i+L-1;
if(j == n) continue;
m[i][j] = Integer.MAX_VALUE;
for (k=i; k<=j-1; k++) {
// q = cost/scalar multiplications
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
m[i][j] = q;
}
}
}
return m[1][n-1];
}
// Driver program to test above function
public static void main(String args[]) {
int arr[] = new int[] {1, 2, 3, 4};
int size = arr.length;
System.out.println("Minimum number of multiplications is "+
MatrixChainOrder(arr, size));
}
}