Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

Matrix chain multiplication 🌟🌟

Steps

  1. Start with entire array.
  2. Try all possible partitions.
  3. Return the best possible two partitions.

Recursive Approach

Code

int f(int i, int j, vector<int>& arr)
{
    if (i == j)
        return 0;
    int mn = INT_MAX;
    for (int k = i; k <= j - 1; k++) {
        int first = f(i, k, arr);
        int second = f(k + 1, j, arr);
        int steps = first + second + arr[i - 1] * arr[k] * arr[j];
        mn = min(mn, steps);
    }
    return mn;
}

int matrixMultiplication(vector<int>& arr, int N)
{
    return f(1, N - 1, arr);
}

Memoization(top-down)

Code

int f(int i, int j, vector<int>& arr, vector<vector<int>>& dp)
{
    if (i == j)
        return 0;
    if (dp[i][j] != -1)
        return dp[i][j];
    int mn = INT_MAX;
    for (int k = i; k <= j - 1; k++) {
        int first = f(i, k, arr, dp);
        int second = f(k + 1, j, arr, dp);
        int steps = first + second + arr[i - 1] * arr[k] * arr[j];
        mn = min(mn, steps);
    }
    return dp[i][j] = mn;
}

int matrixMultiplication(vector<int>& arr, int N)
{
    vector<vector<int>> dp(N, vector<int>(N, -1));
    return f(1, N - 1, arr, dp);
}