Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?

Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?
p = [5, 10, 3, 12, 5, 50, 6]
n = len(p) - 1
m = [[0] * n for _ in range(n)]
for L in range(2, n + 1):
    for i in range(n - L + 1):
        j = i + L - 1
        m[i][j] = min(m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1] for k in range(i, j))
print(m[0][n - 1], m[0][1])
  1. A. 2010 150
  2. B. 2010 600
  3. C. 2110 150
  4. D. 1800 150

Correct answer: A. 2010 150

m[0][1] = 5·10·3 = 150 for the first pair. Filling the table by chain length gives 2010 for the whole chain. Trying all parenthesisations is Catalan(n − 1) – exponential – while the DP is O(n³).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic