text: Maximum profit after buying and selling the stocks with transaction fees | Set 2 | Java program for the above approach ; Function to find the maximum profit with transaction fee ; Traversing the stocks for each day ; Update buy and sell ; Return the maximum profit ; Driver code ; Given Input ; Function Call
code: import java . io . * ; class GFG { static int MaxProfit ( int arr [ ] , int n , int transactionFee ) { int buy = - arr [ 0 ] ; int sell = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int temp = buy ; buy = Math . max ( buy , sell - arr [ i ] ) ; sell = Math . max ( sell , temp + arr [ i ] - transactionFee ) ; } return Math . max ( sell , buy ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 1 , 7 , 2 , 8 , 4 } ; int n = arr . length ; int transactionFee = 2 ; System . out . println ( MaxProfit ( arr , n , transactionFee ) ) ; } }