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?- A. 15125
- B. 47500
- C. 21375
- 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
- Game of two eggs and 100 floors: you have two identical eggs and must find the highest floor from which a dropped egg survives, using as…
- Array b = [9, 2, 7, 4, 1, 8, 3]. Count the pairs (i < j) with b[i] > 2·b[j] (a reverse pair). Run the brute-force code. python…
- For the array c = [1, 2, 3, 4], consider every non-empty subarray and its XOR value. How many subarrays have an XOR value that is strictly…
- For the string "character", find the length of its longest palindromic subsequence (characters need not be adjacent, but must keep their…
- Count the subarrays of w = [1, 3, 2, 5, 4, 4, 2] whose maximum minus minimum is at most 3. Run the brute-force count. python…
- What is the minimum number of perfect squares (1, 4, 9, 16, ...) whose sum is exactly 12? Run the DP over all squares not exceeding 12…