Suppose we have two lists called weights and values which are of same length and another number called capacity k. Here weights[i] and values[i] shows the weight and value of the ith item. Now, we can take at most k capacity weights, and that we can only take at most one copy of each item, we have to find the maximum amount of value we can get.
So, if the input is like weights = [2, 3, 4], values = [2, 6, 4], capacity = 6, then the output will be 8
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): n=len(weights) dp=[[0 for i in range(capacity+1)] for _ in range(n+1)] for i in range(n+1): for j in range(capacity+1): if i==0 or j==0: dp[i][j]=0 elif weights[i-1]<=j: dp[i][j]=max(dp[i-1][j-weights[i-1]]+values[i-1],dp[i-1][j]) else: dp[i][j]=dp[i-1][j] return dp[n][capacity] ob = Solution() weights = [2, 3, 4] values = [2, 6, 4] capacity = 6 print(ob.solve(weights, values, capacity))
[2, 3, 4], [2, 6, 4], 6