Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute the product.
Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute the product.
def mcm(d):
n = len(d) - 1; dp = [[0] * (n + 1) for _ in range(n + 1)]
for L in range(2, n + 1):
for i in range(1, n - L + 2):
j = i + L - 1
dp[i][j] = min(dp[i][k] + dp[k+1][j] + d[i-1]*d[k]*d[j] for k in range(i, j))
return dp[1][n]
print(mcm([5, 10, 3, 12, 5, 50, 6]))What is printed?- A. 2010
- B. 2346
- C. 3990
- D. 1860
Correct answer: A. 2010
Interval DP over chain lengths: dp[i][j] tries every split k and adds the cost d[i−1]·d[k]·d[j] of the final product. Filling the table by increasing chain length gives 2010, the same as an exhaustive memoised search over all parenthesisations; multiplying left to right costs far more.
More Coding Interview Problems questions
- Problem: With e identical eggs, find the minimum number of drops that always identifies the critical floor of an f-floor building. The…
- Problem: Count the ways to place n non-attacking queens on an n × n board. python def queens(n): cols, d1, d2 = set(), set(), set() def…
- Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings…
- Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space. python def…
- Building a binary heap from n given keys: what are the worst-case costs of (i) bottom-up heapify and (ii) n successive inserts into an…
- In Java 8+, many keys that are Comparable and all land in ONE HashMap bucket. What is the worst-case cost of get() on that bucket once it…