Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give?

0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give?
items = [(10, 60), (20, 100), (30, 120)]
W = 50
cap, g = W, 0
for w, v in sorted(items, key=lambda x: -x[1] / x[0]):
    if w <= cap: cap -= w; g += v
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(g, dp[W])
  1. A. 220 220
  2. B. 160 240
  3. C. 160 220
  4. D. 180 220

Correct answer: C. 160 220

Greedy by value/weight takes 10 (6/unit) and 20 (5/unit) for 160 and cannot fit 30. The DP finds 20 + 30 = 220. Greedy is optimal only for the fractional knapsack, where it would take 2/3 of the 30-kg item for 240.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic