Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute the product.

Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute the product.
def mcm(d):
    n = len(d) - 1; dp = [[0] * (n + 1) for _ in range(n + 1)]
    for L in range(2, n + 1):
        for i in range(1, n - L + 2):
            j = i + L - 1
            dp[i][j] = min(dp[i][k] + dp[k+1][j] + d[i-1]*d[k]*d[j] for k in range(i, j))
    return dp[1][n]
print(mcm([5, 10, 3, 12, 5, 50, 6]))
What is printed?
  1. A. 2010
  2. B. 2346
  3. C. 3990
  4. D. 1860

Correct answer: A. 2010

Interval DP over chain lengths: dp[i][j] tries every split k and adds the cost d[i−1]·d[k]·d[j] of the final product. Filling the table by increasing chain length gives 2010, the same as an exhaustive memoised search over all parenthesisations; multiplying left to right costs far more.

More Coding Interview Problems questions

Exams that ask this topic