Find Maximum Profit After Buying and Selling Stocks Twice 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 

Live Demo

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
Updated on: 2020-12-02T05:48:17+05:30

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements