text: Maximum profit after buying and selling the stocks with transaction fees | Set 2 | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; 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 = max ( buy , sell - arr [ i ] ) ; sell = max ( sell , temp + arr [ i ] - transactionFee ) ; } return max ( sell , buy ) ; } int main ( ) { int arr [ ] = { 6 , 1 , 7 , 2 , 8 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int transactionFee = 2 ; cout << MaxProfit ( arr , n , transactionFee ) ; return 0 ; }