Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications.
Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications.
def mcm(p):
n = len(p) - 1
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 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]), mcm([40, 20, 30, 10, 30]))What is printed?- A. 27000 26000
- B. 4500 26000
- C. 4500 30000
- D. 9000 26000
Correct answer: B. 4500 26000
Interval DP over the split point k. For 10×30, 30×5, 5×60: (AB)C = 10·30·5 + 10·5·60 = 1500 + 3000 = 4500, while A(BC) = 30·5·60 + 10·30·60 = 27000. Second chain: 26000. O(n³) time, O(n²) space.
More Coding Interview Problems questions
- Problem: A DP solution for 'minimum coins for amount A using c denominations' with A ≤ 10⁴ and c ≤ 100 is accepted. A friend proposes…
- Problem: Find the largest square of 1s in a binary matrix and return its area. python def square(m): R, C = len(m), len(m[0]); dp = [[0]…
- Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit. python def cooldown(p): hold…
- Problem: Count the number of distinct ways to reach target t by putting + or − in front of every number. python from functools import…
- Problem: Generate all subsets of a set of feature flags (backtracking) and count those whose sum equals a target. python def count(a, t…
- Problem: Generate all permutations of a list that may contain duplicates, without repeats. How many are produced? python def perms(a)…