Skip to content

Add Matrix Chain Multiplication optimised approach #5753

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/main/java/com/thealgorithms/misc/MCM.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Dynamic Programming Java implementation of Matrix
// Chain Multiplication.
// See the Cormen book for details of the following
// algorithm
import java.util.*;
import java.io.*;
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 code
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));
}
}
/* This code is contributed by Rajat Mishra*/
Loading