Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1 (unbounded knapsack).
Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1 (unbounded knapsack).
def rod(price, n):
dp = [0] * (n + 1)
for L in range(1, n + 1):
dp[L] = max(price[i] + dp[L - i - 1] for i in range(L))
return dp[n]
print(rod([2, 5, 7, 8, 10, 13, 15], 7))What is printed?- A. 17
- B. 15
- C. 32
- D. 14
Correct answer: A. 17
Length 2 has the best price per unit (2.5): 2 + 2 + 2 + 1 gives 5 + 5 + 5 + 2 = 17, and 2 + 2 + 3 also gives 17. Selling the rod whole (or allowing each length only once, 0/1 knapsack) gives 15, cutting it into seven unit pieces gives 14, and the index slip dp[L − i] instead of dp[L − i − 1] inflates the result to 32.
More Coding Interview Problems questions
- Problem: Envelopes [w, h] nest only if both dimensions are strictly smaller. Find the longest nesting chain by sorting and then running…
- Problem: Can the array be split into k subsets with equal sums? (Backtracking over bucket fills.) python def can(a, k): s = sum(a) if s %…
- Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c. python def flips(a, b, c): res = 0 while a or b or…
- Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick. python m = 0b101101 s, cnt = m, 0 while s: cnt += 1 s…
- A bitmask DP loops over every mask of n bits and, for each mask, over all of its submasks. What is the total number of (mask, submask)…
- Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element…