Data Structures & AlgorithmsHardCodeforces Div2 D · interval DP
Problem: Multiply a chain of matrices with dimensions p = [10, 30, 5, 60] (matrix i is p[i] by p[i+1]). Find the minimum number of scalar multiplications using this interval DP.
Problem: Multiply a chain of matrices with dimensions p = [10, 30, 5, 60] (matrix i is p[i] by p[i+1]). Find the minimum number of scalar multiplications using this interval DP.
def mcm(p):
n = len(p) - 1
dp = [[0] * n for _ in range(n)]
for L in range(2, n + 1):
for i in range(n - L + 1):
j = i + L - 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]))What is printed?- A. 27000
- B. 4500
- C. 9000
- D. 18000
Correct answer: B. 4500
Parenthesising as (AB)C costs 1500 + 3000 = 4500, which beats A(BC) at 27000. The interval DP tries every split point k.
More Coding Interview Problems questions
- Problem: How many ways can 10 be formed as an ordered-free sum of coins 1, 2 and 5 (each coin may be used any number of times, and order…
- Problem: What is the diameter (in edges) of the tree with edges 1-2, 2-3, 2-4, 4-5, 5-6? Use the double BFS code. python from collections…
- Problem: A robot starts at (0, 0) facing north (+y). Commands: F moves one step forward, B one step backward (facing unchanged), L turns…
- Problem: What is the KMP prefix-function array pi for the string 'ababaca'? python s = 'ababaca' pi = [0] len(s) for i in range(1…
- Problem: What is the lexicographically smallest rotation of 'bcabca'? python s = 'bcabca' print(min(s[i:] + s[:i] for i in range(len(s))))…
- Problem: Items (weight, value) are (2,3), (3,4), (4,5), and each may be used at most once. Capacity W = 7. Run the code below to find the…