Question: Write a function to implement the Knapsack problem. The function should take in a list of items, each with a weight and a value, and
Write a function to implement the Knapsack problem. The function should take in a list of items, each with a weight and a value, and a maximum weight capacity, and return the maximum total value that can be obtained by selecting items such that the total weight of the items is less than or equal to the maximum weight capacity. The function should first sort the items by value-to-weight ratio and then use dynamic programming to solve the problem.
Example:
Input:
items = [
{"name": "item1", "weight": 2, "value": 6},
{"name": "item2", "weight": 2, "value": 10},
{"name": "item3", "weight": 3, "value": 12},
{"name": "item4", "weight": 5, "value": 20},
{"name": "item5", "weight": 9, "value": 22}
]
max_weight = 20
Output: 36
Explanation: The maximum total value that can be obtained by selecting items such that the total weight is less than or equal to 20 is 36, which is obtained by selecting "item2" and "item4".
Step by Step Solution
3.40 Rating (169 Votes )
There are 3 Steps involved in it
The detailed ... View full answer
Get step-by-step solutions from verified subject matter experts
