Maximum profit after buying and selling stocks with transaction fees | PHP implementation of above approach ; b [ 0 ] will contain the maximum profit ; b [ 1 ] will contain the day on which we are getting the maximum profit ; here finding the max profit ; if we get less then or equal to zero it means we are not getting the profit ; check if sum is greater then maximum then store the new maximum ; Driver code
< ? php function max_profit ( & $ a , & $ b , $ n , $ fee ) { $ diff_day = 1 ; $ sum = 0 ; $ b [ 0 ] = 0 ; $ b [ 1 ] = $ diff_day ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ l = 0 ; $ r = $ diff_day ; $ sum = 0 ; for ( $ j = $ n - 1 ; $ j >= $ i ; $ j -- ) { $ profit = ( $ a [ $ r ] - $ a [ $ l ] ) - $ fee ; if ( $ profit > 0 ) { $ sum = $ sum + $ profit ; } $ l ++ ; $ r ++ ; } if ( $ b [ 0 ] < $ sum ) { $ b [ 0 ] = $ sum ; $ b [ 1 ] = $ diff_day ; } $ diff_day ++ ; } } $ arr = array ( 6 , 1 , 7 , 2 , 8 , 4 ) ; $ n = sizeof ( $ arr ) ; $ b = array ( ) ; $ tranFee = 2 ; max_profit ( $ arr , $ b , $ n , $ tranFee ) ; echo ( $ b [ 0 ] ) ; echo ( " , ▁ " ) ; echo ( $ b [ 1 ] ) ; ? >