Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications.

Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications.
def mcm(p):
    n = len(p) - 1
    dp = [[0] * n for _ in range(n)]
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            dp[i][j] = min(dp[i][k] + dp[k+1][j] + p[i] * p[k+1] * p[j+1] for k in range(i, j))
    return dp[0][n - 1]
print(mcm([10, 30, 5, 60]), mcm([40, 20, 30, 10, 30]))
What is printed?
  1. A. 27000 26000
  2. B. 4500 26000
  3. C. 4500 30000
  4. D. 9000 26000

Correct answer: B. 4500 26000

Interval DP over the split point k. For 10×30, 30×5, 5×60: (AB)C = 10·30·5 + 10·5·60 = 1500 + 3000 = 4500, while A(BC) = 30·5·60 + 10·30·60 = 27000. Second chain: 26000. O(n³) time, O(n²) space.

More Coding Interview Problems questions

Exams that ask this topic