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?- A. 8
- B. 12
- C. 9
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Two DP loops count ways to pay 5 using coins 1 and 2 (the order of coins in the sum is ignored in the first version). python coins = [1…
- A monotonic deque computes the minimum of each window of size 3. python from collections import deque a = [4, 2, 12, 11, -5, 7] k = 3 dq =…
- A DP counts the minimum number of coins to pay exactly 11 with coins [2, 5], returning −1 if impossible. python INF = float('inf') coins =…
- A binary search finds the largest x with xx <= 50 using the bounds 0 and 50. python lo, hi = 0, 50 while lo < hi: mid = (lo + hi + 1) // 2…
- A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum. python a = [3, -1, 4, -6…
- A problem asks for the minimum number of refuelling stops on a road, where the car has a fuel capacity and each station offers some fuel…