Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

GATE | GATE-CS-2003 | Question 90

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Consider the following dynamic programming code snippet for solving the 0/1 Knapsack problem:


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)
        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)?









Answer: (D)


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

My Personal Notes arrow_drop_up
Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads