Maximum profit by buying and selling a stock at most twice | Set 2 | Python3 implmenetation to find maximum possible profit with at most two transactions ; Function to find the maximum profit with two transactions on a given list of stock prices ; Set initial buying values to INT_MAX as we want to minimize it ; Set initial selling values to zero as we want to maximize it ; Money lent to buy the stock should be minimum as possible . buy1 tracks the minimum possible stock to buy from 0 to i - 1. ; Profit after selling a stock should be maximum as possible . profit1 tracks maximum possible profit we can make from 0 to i - 1. ; Now for buying the 2 nd stock , we will integrate profit made from selling the 1 st stock ; Profit after selling a 2 stocks should be maximum as possible . profit2 tracks maximum possible profit we can make from 0 to i - 1. ; Driver code
import sys NEW_LINE def maxProfit ( price , n ) : NEW_LINE INDENT buy1 , buy2 = sys . maxsize , sys . maxsize NEW_LINE profit1 , profit2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT buy1 = min ( buy1 , price [ i ] ) NEW_LINE profit1 = max ( profit1 , price [ i ] - buy1 ) NEW_LINE buy2 = min ( buy2 , price [ i ] - profit1 ) NEW_LINE profit2 = max ( profit2 , price [ i ] - buy2 ) NEW_LINE DEDENT return profit2 NEW_LINE DEDENT price = [ 2 , 30 , 15 , 10 , 8 , 25 , 80 ] NEW_LINE n = len ( price ) NEW_LINE print ( " Maximum ▁ Profit ▁ = ▁ " , maxProfit ( price , n ) ) NEW_LINE