
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find maximum value we can get in knapsack problem by taking multiple copies in Python
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
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
- Related Questions & Answers
- Program to find maximum amount we can get by taking different items within the capacity in Python
- Program to find the maximum profit we can get by buying on stock market multiple times in Python
- Program to find maximum credit we can get by finishing some assignments in python
- Program to implement the fractional knapsack problem in Python
- Python Program for 0-1 Knapsack Problem
- Program to find maximum price we can get by holding items into a bag in Python
- Program to find maximum score we can get in jump game in Python
- Fractional Knapsack Problem
- Program to find the maximum profit we can get by buying on stock market once in Python
- Program to find maximum number of coins we can get using Python
- Program to find maximum profit we can get by buying and selling stocks with a fee in Python?
- Program to find maximum coins we can get from disappearing coins matrix in Python
- C++ Program to Solve the Fractional Knapsack Problem
- Program to find maximum profit we can make by buying and selling stocks in Python?
- Program to find maximum profit we can make by holding and selling profit in Python
Advertisements