Skip to content

Create Matrix Chain_Multiplication.java #30

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

Merged
merged 1 commit into from
Oct 1, 2022
Merged
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
54 changes: 54 additions & 0 deletions Java/Matrix Chain_Multiplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Memoization
public class Solution {
public static int matrixMultiplication(int[] arr , int N) {
if(N < 3) return 0;

int[][] dp = new int[N][N];
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
dp[i][j] = -1;

return partition(1, N-1, arr, dp);
}

private static int partition(int i, int j, int[] arr, int[][] dp) {
if(i == j) return 0;

if(dp[i][j] != -1) return dp[i][j];

int min = Integer.MAX_VALUE;

for(int k = i; k < j; k++) {
int curr = (arr[i-1] * arr[k] * arr[j]) +
partition(i, k, arr, dp) + partition(k+1, j, arr, dp);
min = Math.min(min, curr);
}

return dp[i][j] = min;
}
}

// Tabulation
public class Solution {
public static int matrixMultiplication(int[] arr , int N) {
if(N < 3) return 0;

int[][] dp = new int[N][N];

for(int i = N-1; i > 0; i--) {
for(int j = i+1; j < N; j++) {
if(i == j) continue;

int min = (int) 1e9;
for(int k = i; k < j; k++) {
min = Math.min(min, (arr[i-1] * arr[k] * arr[j]) +
dp[i][k] + dp[k+1][j]);
}

dp[i][j] = min;
}
}

return dp[1][N-1];
}
}