|
| 1 | +# Matrix Chain Multiplication |
| 2 | +Question -> [Matrix Chain Multiplication](https://www.codingninjas.com/codestudio/problems/matrix-chain-multiplication_975344) |
| 3 | + |
| 4 | +### Recursion |
| 5 | +```java |
| 6 | +public class Solution { |
| 7 | + public static int matrixMultiplication(int[] arr , int N) { |
| 8 | + return func(1, N-1, arr); |
| 9 | + } |
| 10 | + private static int func(int i, int j, int[] arr) { |
| 11 | + if(i==j) return 0; |
| 12 | + int min = Integer.MAX_VALUE; |
| 13 | + for(int k=i; k<j; k++) { |
| 14 | + int value = (arr[i-1]*arr[k]*arr[j]) + func(i,k,arr) + func(k+1,j,arr); |
| 15 | + if(value<min) min = value; |
| 16 | + } |
| 17 | + return min; |
| 18 | + } |
| 19 | +} |
| 20 | +``` |
| 21 | +> `Time Complexity` : **Exponential** |
| 22 | +> `Space Complexity` : **O(N)** |
| 23 | +--- |
| 24 | +### Memoization |
| 25 | +```java |
| 26 | +import java.util.*; |
| 27 | +public class Solution { |
| 28 | + public static int matrixMultiplication(int[] arr , int N) { |
| 29 | + int[][] dp = new int[N][N]; |
| 30 | + for(int[] row : dp) Arrays.fill(row,-1); |
| 31 | + return func(1, N-1, arr, dp); |
| 32 | + } |
| 33 | + private static int func(int i, int j, int[] arr, int[][] dp) { |
| 34 | + if(i==j) return 0; |
| 35 | + if(dp[i][j] != -1) return dp[i][j]; |
| 36 | + int min = Integer.MAX_VALUE; |
| 37 | + for(int k=i; k<j; k++) { |
| 38 | + int value = (arr[i-1]*arr[k]*arr[j]) + func(i,k,arr,dp) + func(k+1,j,arr,dp); |
| 39 | + if(value<min) min = value; |
| 40 | + } |
| 41 | + return dp[i][j] = min; |
| 42 | + } |
| 43 | +} |
| 44 | +``` |
| 45 | +> `Time Complexity` : **O(N<sup>3</sup>)** |
| 46 | +> `Space Complexity` : **O(N)+O(N\*N)**, for Recursion Stack and dp array |
| 47 | +--- |
| 48 | +### Tabulation |
| 49 | +```java |
| 50 | +public class Solution { |
| 51 | + public static int matrixMultiplication(int[] arr , int N) { |
| 52 | + int[][] dp = new int[N][N]; |
| 53 | + //base case |
| 54 | + for(int i=1; i<N; i++) dp[i][i] = 0; |
| 55 | + for(int i=N-1; i>=1; i--) { |
| 56 | + for(int j=i+1; j<N; j++) { |
| 57 | + int min = Integer.MAX_VALUE; |
| 58 | + for(int k=i; k<j; k++) { |
| 59 | + int value = (arr[i-1]*arr[k]*arr[j]) + dp[i][k] + dp[k+1][j]; |
| 60 | + if(value<min) min = value; |
| 61 | + } |
| 62 | + dp[i][j] = min; |
| 63 | + } |
| 64 | + } |
| 65 | + return dp[1][N-1]; |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
| 69 | +> `Time Complexity` : **O(N<sup>3</sup>)** |
| 70 | +> `Space Complexity` : **O(N\*N)** |
| 71 | +--- |
| 72 | +Video Explanations -> [Memoization](https://youtu.be/vRVfmbCFW7Y?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY), [Tabulation](https://youtu.be/pDCXsbAw5Cg?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) |
| 73 | +<hr> |
0 commit comments