Categories
interview

Matrix Chain Multiplication

const matrixChainMultiplication = (matrix, n) => {
  const dp = Array(100).fill(0).map(x => Array(100).fill(-1));
  // Ai Matrix dimensions = (i - 1) x (i)
  return MCM(matrix, 1, n - 1, dp);
};

const MCM = (matrix, i, j, dp) => {
  if (i === j) {
    return 0;
  }
  if (dp[i][j] !== -1) {
    return dp[i][j];
  }
  dp[i][j] = Number.MAX_VALUE;
  for (let k = i; k < j; k++) {
    dp[i][j] = Math.min(dp[i][j],
      MCM(matrix, i, k, dp) + MCM(matrix, k + 1, j, dp) + (matrix[i - 1] * matrix[k] * matrix[j]));
  }
  return dp[i][j];
};

const test = [1, 2, 3, 4, 3];
console.log(matrixChainMultiplication(test, test.length)); // 30

Demo