Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: 0/1 knapsack with a 1-D array. The candidate below loops capacity upwards.
Problem: 0/1 knapsack with a 1-D array. The candidate below loops capacity upwards.
def wrong(w, v, W):
dp = [0] * (W + 1)
for i in range(len(w)):
for c in range(w[i], W + 1):
dp[c] = max(dp[c], dp[c - w[i]] + v[i])
return dp[W]
def right(w, v, W):
dp = [0] * (W + 1)
for i in range(len(w)):
for c in range(W, w[i] - 1, -1):
dp[c] = max(dp[c], dp[c - w[i]] + v[i])
return dp[W]
print(wrong([2, 3], [3, 4], 6), right([2, 3], [3, 4], 6))What is printed?- A. 9 7
- B. 7 7
- C. 9 9
- D. 8 7
Correct answer: A. 9 7
Iterating upwards lets dp[c − w] already include item i, so an item can be taken repeatedly: three copies of weight 2 give 9 (that is the unbounded knapsack). Downwards iteration reads only values from the previous item, so each is used once: 3 + 4 = 7. O(n·W).
More Coding Interview Problems questions
- Problem: 0/1 knapsack – maximise value within capacity W. cpp int knap(vector<int> w, vector<int> v, int W) { vector<int> dp(W + 1, 0)…
- Problem: Find the length of the longest strictly increasing subsequence of daily sales. python from bisect import bisectleft def lis(a)…
- Problem: Find the length of the longest common subsequence of two version strings. python def lcs(a, b): dp = [[0] (len(b) + 1) for in…
- Problem: Find the minimum number of insert, delete or replace operations to convert one word to another (edit distance). python def…
- Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell. python def…
- Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down). python def minpath(g): R…