![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 profit we can make after k Buy and Sell in python
Suppose we have a list of numbers called nums that is representing the stock prices of a company in chronological order and we also have another value k, we have to find the maximum profit we can make from up to k buys and sells (We must buy before sell, and sell before buy).
So, if the input is like prices = [7, 3, 5, 2, 3] k = 2, then the output will be 3, as we can buy at 3, then sell at 5, again buy at 2, and sell at 3.
To solve this, we will follow these steps −
- Define a function dp() . This will take i, k, bought
- if i is same as size of prices or k is same as 0, then
- return 0
- if bought is true, then
- return maximum of (dp(i+1, k-1, False) + prices[i]) and dp(i+1, k, bought)
- otherwise,
- return maximum of (dp(i+1, k, True) - prices[i]) and dp(i + 1, k, bought)
- From the main method call dp(0, k, False) and return result
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, prices, k): def dp(i, k, bought): if i == len(prices) or k == 0: return 0 if bought: return max(dp(i + 1, k - 1, False) + prices[i], dp(i + 1, k, bought)) else: return max(dp(i + 1, k, True) - prices[i], dp(i + 1, k, bought)) return dp(0, k, False) ob = Solution() prices = [7, 3, 5, 2, 3] k = 2 print(ob.solve(prices, k))
Input
[7, 3, 5, 2, 3], 2
Output
3
Advertisements