Maximize profit in buying and selling stocks with Rest condition | Python3 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
def maxProfit ( prices , n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT rest = [ 0 ] * n NEW_LINE hold = [ 0 ] * n NEW_LINE sold = [ 0 ] * n NEW_LINE rest [ 0 ] = 0 NEW_LINE hold [ 0 ] = - prices [ 0 ] NEW_LINE sold [ 0 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT rest [ i ] = max ( rest [ i - 1 ] , sold [ i - 1 ] ) NEW_LINE hold [ i ] = max ( hold [ i - 1 ] , rest [ i - 1 ] - prices [ i ] ) NEW_LINE sold [ i ] = hold [ i - 1 ] + prices [ i ] NEW_LINE DEDENT return max ( rest [ n - 1 ] , sold [ n - 1 ] ) NEW_LINE DEDENT price = [ 2 , 4 , 5 , 0 , 2 ] NEW_LINE n = len ( price ) NEW_LINE print ( maxProfit ( price , n ) ) NEW_LINE