Data Structures & AlgorithmsVery hardCodeforces Div2 C/D · Amazon SDE OA

Items (weight, value) are (5,10), (4,7), (6,12), (3,4) and the knapsack capacity is 10. Each item may be taken at most once. Run the exact 0/1 knapsack DP and report the best value.

Items (weight, value) are (5,10), (4,7), (6,12), (3,4) and the knapsack capacity is 10. Each item may be taken at most once. Run the exact 0/1 knapsack DP and report the best value.
items=[(5,10),(4,7),(6,12),(3,4)]
W=10
dp=[0]*(W+1)
for w,v in items:
    for c in range(W,w-1,-1):
        dp[c]=max(dp[c],dp[c-w]+v)
print(dp[W])
What is printed?
  1. A. 19
  2. B. 17
  3. C. 20
  4. D. 22

Correct answer: A. 19

The exact 0/1 DP iterates capacities downward so each item is used once. Density greedy is not exact here, unbounded knapsack lets an item repeat (5+5 gives 20), and reading the capacity as 11 is an off-by-one slip.

More Coding Interview Problems questions

Exams that ask this topic