Program to find maximum value we can get in knapsack problem by taking multiple copies in Python

PythonServer Side ProgrammingProgramming

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 −

  • Define a function dp() . This will take i, k
  • if i is same as size of weights , then
    • return 0
  • ans := dp(i + 1, k)
  • if k >= weights[i], then
    • ans := maximum of ans and dp(i, k - weights[i]) + values[i]
  • return ans
  • From the main method do the following −
  • return dp(0, capacity)

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

[1, 2, 3], [1,5,3], 5

Output

11
raja
Published on 20-Oct-2020 11:09:00
Advertisements