![]() |
VOOZH | about |
Given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity, the task is to determine the maximum value that can be obtained by putting items into the knapsack. In the Unbounded Knapsack problem, you can use each item as many times as you want.
Example:
Input: Weights:
[1, 3, 4, 5], Values:[10, 40, 50, 70], Capacity:8Output:The maximum value obtainable is: 140Input: Weights:
[2, 3, 5], Values:[15, 20, 30], Capacity:7Output: The maximum value obtainable is: 140
To solve the Unbounded Knapsack problem, we use a dynamic programming approach. We define a
dparray wheredp[i]represents the maximum value that can be achieved with a knapsack capacityi.
dp array of size W+1 with all elements set to 0. This array will store the maximum value that can be achieved for each capacity from 0 to W.0 to W. For each capacity i, we check all items to see if they can fit into the knapsack.i), we update the dp array at position i to be the maximum of its current value or the value obtained by including the item. This is calculated as dp[i - weights[j]] + values[j].dp[W] will be the maximum value that can be achieved with the given weight capacity W.Below is the Python code to implement the Unbounded Knapsack problem:
Maximum value: 110
n is the number of items and W is the maximum capacity of the knapsack. This is because we iterate through each capacity and for each capacity, we iterate through all items.dp array used to store the maximum value for each capacity.