-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathMCM.java
More file actions
23 lines (21 loc) · 719 Bytes
/
MCM.java
File metadata and controls
23 lines (21 loc) · 719 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class MCM {
public static int matrixChainOrder(int[] p) {
int n = p.length;
int[][] dp = new int[n][n];
for (int len = 2; len < n; len++) {
for (int i = 1; i < n - len + 1; i++) {
int j = i + len - 1;
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j];
dp[i][j] = Math.min(dp[i][j], cost);
}
}
}
return dp[1][n - 1];
}
public static void main(String[] args) {
int[] arr = {40, 20, 30, 10, 30};
System.out.println(matrixChainOrder(arr));
}
}