Data Structures & AlgorithmsVery hardGATE CS · ICPC regional

A knapsack routine is written as follows (items are (weight, value)).

A knapsack routine is written as follows (items are (weight, value)).
items = [(2, 3), (3, 4), (4, 5)]
W = 6
dp = [0] * (W + 1)
for w, v in items:
    for c in range(w, W + 1):
        dp[c] = max(dp[c], dp[c - w] + v)
print(dp[W])
What is printed?
  1. A. 8
  2. B. 12
  3. C. 9
  4. D. 5

Correct answer: C. 9

The printed value is the 0/1 knapsack optimum. The correct version scans capacities downward so an item is not reused; the upward loop used as shown is the unbounded knapsack, which may take an item twice, and it prints a larger value.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic