Maximum profit by buying and selling a stock at most twice | Set 2 | Function to find the maximum profit with two transactions on a given list of stock prices ; buy1 - Money lent to buy 1 stock profit1 - Profit after selling the 1 st stock buyed . buy2 - Money lent to buy 2 stocks including profit of selling 1 st stock profit2 - Profit after selling 2 stocks ; Set initial buying values to Number . MAX_VALUE 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
function maxProfit ( price , n ) { var buy1 , profit1 , buy2 , profit2 ; buy1 = buy2 = Number . MAX_VALUE ; profit1 = profit2 = 0 ; for ( i = 0 ; i < n ; i ++ ) { buy1 = Math . min ( buy1 , price [ i ] ) ; profit1 = Math . max ( profit1 , price [ i ] - buy1 ) ; buy2 = Math . min ( buy2 , price [ i ] - profit1 ) ; profit2 = Math . max ( profit2 , price [ i ] - buy2 ) ; } return profit2 ; } var price = [ 2 , 30 , 15 , 10 , 8 , 25 , 80 ] ; var n = price . length ; document . write ( " " + maxProfit ( price , n ) ) ;