Data Structures & AlgorithmsVery hardCodeforces Div2 D · knapsack

Problem: Items (weight, value) are (2,3), (3,4), (4,5), and each may be used at most once. Capacity W = 7. Run the code below to find the maximum value.

Problem: Items (weight, value) are (2,3), (3,4), (4,5), and each may be used at most once. Capacity W = 7. Run the code below to find the maximum value.
items = [(2, 3), (3, 4), (4, 5)]
W = 7
best = [0] * (W + 1)
for w, v in items:
    for c in range(W, w - 1, -1):
        best[c] = max(best[c], best[c - w] + v)
print(best[W])
What is printed?
  1. A. 10
  2. B. 12
  3. C. 8
  4. D. 9

Correct answer: D. 9

Each item is used at most once, so the best set at capacity 7 is {3, 4} with value 4 + 5 = 9 (the pair {2, 4} gives 8 and {2, 3} gives 7). Letting items repeat would give 10 via 2 + 2 + 3, which is the trap for unbounded knapsack.

More Coding Interview Problems questions

Exams that ask this topic