Program to find maximum amount we can get by taking different items within the capacity in Python

PythonServer Side ProgrammingProgramming

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 −

  • n:= size of weights
  • dp:= a matrix of size capacity x n, and fill with 0
  • for i in range 0 to n, do
    • for j in range 0 to capacity, do
      • if i is same as 0 or j is same as 0, then
        • dp[i, j]:= 0
      • otherwise when weights[i-1] <= j, then
        • dp[i,j] = maximum of (dp[i-1, j-weights[i - 1]] + values[i-1]) and (dp[i-1, j])
      • otherwise,
        • dp[i, j]:= dp[i-1, j]
  • return dp[n, capacity]

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, weights, values, capacity):
      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:
                  elif weights[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


Updated on 05-Oct-2020 12:15:03