Program to find maximum price we can get by holding items into a bag in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists of numbers. One is called weights and another is called values. These are of same length, We also have two values called capacity and count. Here weights[i] and values[i] represent the weight and value of the ith item. We can hold at most capacity weight and at most count items in total, and we can take only one copy of each item, so we have to find the maximum amount of value we can get.

So, if the input is like weights = [2, 2, 4, 6] values = [15, 15, 20, 35] capacity = 8 count = 3, then the output will be 50, as we can select first 3 items, since the total weight is 8.

To solve this, we will follow these steps −

  • items := a list of pairs by taking weights and values

  • Define a function dp() . This will take i, cp, ct

  • if i is same as size of items or ct is same as 0, then

    • return 0.0

  • (w, v) := items[i]

  • ans := dp(i + 1, cp, ct)

  • if cp >= w, then

    • ans := maximum of ans, dp(i + 1, cp - w, ct - 1) + v

  • return ans

  • From the main method return dp(0, capacity, count)

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def solve(self, weights, values, capacity, count):
      items = list(zip(weights, values))
      def dp(i, cp, ct):
         if i == len(items) or ct == 0:
            return 0.0
         w, v = items[i]
         ans = dp(i + 1, cp, ct)
         if cp >= w:
            ans = max(ans, dp(i + 1, cp - w, ct - 1) + v)
         return ans
      return int(dp(0, capacity, count))
ob = Solution()
weights = [2, 2, 4, 6]
values = [15, 15, 20, 35]
capacity = 8
count = 3
print(ob.solve(weights, values, capacity, count))

Input

[2, 2, 4, 6], [15, 15, 20, 35], 8, 3

Output

50
raja
Published on 22-Dec-2020 06:25:56
Advertisements