Maximize profit in buying and selling stocks with Rest condition | JavaScript program for the above problem ; If there is only one day for buying and selling no profit can be made ; Array to store Maxprofit by resting on given day ; Array to store Maxprofit by buying or resting on the given day ; Array to store Maxprofit by selling on given day ; Initially there will 0 profit ; Buying on 1 st day results in negative profit ; zero profit since selling before buying isn 't possible ; max of profit on ( i - 1 ) th day by resting and profit on ( i - 1 ) th day by selling . ; max of profit by resting on ith day and buying on ith day . ; max of profit by selling on ith day ; maxprofit ; Driver Code
function maxProfit ( prices , n ) { if ( n <= 1 ) return 0 ; let rest = [ ] ; for ( let k = 0 ; k < n ; k ++ ) rest . push ( 0 ) ; let hold = [ ] ; for ( let k = 0 ; k < n ; k ++ ) hold . push ( 0 ) ; let sold = [ ] ; for ( let k = 0 ; k < n ; k ++ ) sold . push ( 0 ) ; rest [ 0 ] = 0 ; hold [ 0 ] = - prices [ 0 ] ; sold [ 0 ] = 0 ; for ( let i = 1 ; i < n ; i ++ ) { rest [ i ] = Math . max ( rest [ i - 1 ] , sold [ i - 1 ] ) ; hold [ i ] = Math . max ( hold [ i - 1 ] , rest [ i - 1 ] - prices [ i ] ) ; sold [ i ] = hold [ i - 1 ] + prices [ i ] ; } return Math . max ( rest [ n - 1 ] , sold [ n - 1 ] ) ; } let price = [ 2 , 4 , 5 , 0 , 2 ] ; let n = price . length ; document . write ( maxProfit ( price , n ) , ' ' ) ;