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?
  1. A. 9 7
  2. B. 7 7
  3. C. 9 9
  4. 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

Exams that ask this topic