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 −
Let us see the following implementation to get better understanding −
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))
[2, 6, 3, 4, 2, 9]