GATE | GATE-CS-2003 | Question 90
Consider the following dynamic programming code snippet for solving the 0/1 Knapsack problem:
Python
def knapsack(values, weights, capacity, n): if n = = 0 or capacity = = 0 : return 0 if weights[n - 1 ] > capacity: return knapsack(values, weights, capacity, n - 1 ) else : return max (values[n - 1 ] + knapsack(values, weights, capacity - weights[n - 1 ], n - 1 ), knapsack(values, weights, capacity, n - 1 )) |
Given the values [60, 100, 120] and weights [10, 20, 30], what would be the output of calling knapsack(values, weights, 50, 3)?
(A)
180
(B)
220
(C)
280
(D)
300
Answer: (D)
Explanation:
The output is 220 because the knapsack function, using dynamic programming, selects items from the given values and weights that maximize the total value while not exceeding the knapsack’s weight capacity of 50. Among the available items, the optimal selection would be to include the items with values 60 and 120, which sum up to 180, and the sum of their corresponding weights up to 40, leaving room to include the item with a value of 100. Hence, the total value obtained is 220, which is the highest achievable value given the constraints.
Quiz of this Question
Please comment below if you find anything wrong in the above post
Please Login to comment...