Suppose we have two lists of same length they are called weights and values, and we also have another value capacity. Here weights[i] and values[i] represent the weight and value of the ith item. If we can take at most capacity weights, and that we can take any number of copies for each item, we have to find the maximum amount of value we can get.
So, if the input is like weights = [1, 2, 3], values = [1, 5, 3], capacity = 5, then the output will be 11
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, weights, values, capacity): def dp(i, k): if i == len(weights): return 0 ans = dp(i + 1, k) if k >= weights[i]: ans = max(ans, dp(i, k - weights[i]) + values[i]) return ans return dp(0, capacity) ob = Solution() weights = [1, 2, 3] values = [1, 5, 3] capacity = 5 print(ob.solve(weights, values, capacity))
[1, 2, 3], [1,5,3], 5