Skip to content

Commit 61e4d11

Browse files
authored
initial
1 parent 4ca4062 commit 61e4d11

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

matrixChainMultiply.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/* A naive recursive implementation that simply follows
2+
the above optimal substructure property */
3+
class MatrixChainMultiplication {
4+
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
5+
static int MatrixChainOrder(int p[], int i, int j)
6+
{
7+
if (i == j)
8+
return 0;
9+
10+
int min = Integer.MAX_VALUE;
11+
12+
// place parenthesis at different places between
13+
// first and last matrix, recursively calculate
14+
// count of multiplications for each parenthesis
15+
// placement and return the minimum count
16+
for (int k = i; k < j; k++)
17+
{
18+
int count = MatrixChainOrder(p, i, k)
19+
+ MatrixChainOrder(p, k + 1, j)
20+
+ p[i - 1] * p[k] * p[j];
21+
22+
if (count < min)
23+
min = count;
24+
}
25+
26+
// Return minimum count
27+
return min;
28+
}
29+
30+
// Driver code
31+
public static void main(String args[])
32+
{
33+
int arr[] = new int[] { 1, 2, 3, 4, 3 };
34+
int n = arr.length;
35+
36+
System.out.println(
37+
"Minimum number of multiplications is "
38+
+ MatrixChainOrder(arr, 1, n - 1));
39+
}
40+
}
41+
/* This code is contributed by Rajat Mishra*/

0 commit comments

Comments
 (0)