From 5649edc57b14e9b99e3e84ff191ca832fec68896 Mon Sep 17 00:00:00 2001 From: Clayton <63671653+Claytonx210@users.noreply.github.com> Date: Sat, 1 Oct 2022 00:19:13 +0530 Subject: [PATCH] MatrixChainMultiplication.java Dynamic program --- .../MatrixChainMultiplication.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 dynamic-programming/MatrixChainMultiplication.java diff --git a/dynamic-programming/MatrixChainMultiplication.java b/dynamic-programming/MatrixChainMultiplication.java new file mode 100644 index 00000000..8cf56510 --- /dev/null +++ b/dynamic-programming/MatrixChainMultiplication.java @@ -0,0 +1,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