Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Matrix chain: matrices A1..A6 have dimension sequence p = [30, 35, 15, 5, 10, 20, 25] (Ai is p[i−1] × p[i]). What is the minimum number of scalar multiplications needed to compute the product, using an optimal parenthesization?

Matrix chain: matrices A1..A6 have dimension sequence p = [30, 35, 15, 5, 10, 20, 25] (Ai is p[i−1] × p[i]). What is the minimum number of scalar multiplications needed to compute the product, using an optimal parenthesization?
d=[30,35,15,5,10,20,25]
n=len(d)-1
INF=10**18
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]+d[i]*d[k+1]*d[j+1] for k in range(i,j))
print(m[0][n-1])
What is printed?
  1. A. 15125
  2. B. 47500
  3. C. 21375
  4. D. 58000

Correct answer: A. 15125

Interval DP over splits: cost = left + right + p[i]·p[k+1]·p[j+1]. Always splitting after the first matrix is a greedy that is not optimal, a wrong split dimension changes every term, and maximizing instead of minimizing gives a different number.

More Coding Interview Problems questions

Exams that ask this topic