- 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 after buying and selling stocks at most two times in python
Suppose we have a list of numbers called prices and that is representing the stock prices of a company in chronological order, we have to find the maximum profit we can make from buying and selling that stock at most two times. We have to buy first then sell.
So, if the input is like prices = [2, 6, 3, 4, 2, 9], then the output will be 11, as we can buy at price 2, then sell at 6, again buy at 2, and sell at 9.
To solve this, we will follow these steps −
- first_buy := -inf, first_sell := -inf
- second_buy := -inf, second_sell := -inf
- for each px in prices, do
- first_buy := maximum of first_buy and -px
- first_sell := maximum of first_sell and (first_buy + px)
- second_buy := maximum of second_buy and (first_sell - px)
- second_sell := maximum of second_sell and (second_buy + px)
- return maximum of 0, first_sell and second_sell
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, prices): first_buy = first_sell = float("-inf") second_buy = second_sell = float("-inf") for px in prices: first_buy = max(first_buy, -px) first_sell = max(first_sell, first_buy + px) second_buy = max(second_buy, first_sell - px) second_sell = max(second_sell, second_buy + px) return max(0, first_sell, second_sell) ob = Solution() prices = [2, 6, 3, 4, 2, 9] print(ob.solve(prices))
Input
[2, 6, 3, 4, 2, 9]
Output
11
Advertisements