Advertisement
i_love_rao_khushboo

Best Time to Buy and Sell Stock with Transaction Fee

Sep 19th, 2022
1,078
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. // Problem link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
  2.  
  3. // Useful Reference(s): --->
  4. // https://medium.com/algorithms-and-leetcode/best-time-to-buy-sell-stocks-on-leetcode-the-ultimate-guide-ce420259b323
  5.  
  6. /*********************************************************************************************************/
  7.  
  8. // Method 1 (STATE MACHINE DP)
  9. // Link for ver nice explanation of this approach --->
  10. // https://www.youtube.com/watch?v=pTQB9wbIpfU
  11.  
  12. #include<bits/stdc++.h>
  13. using namespace std;
  14.  
  15. int solve(vector<int> &v, int n, int fee) {
  16.     // prevBSP = previous Bought State Profit
  17.     // prevSSP = previous Sold State Profit
  18.     int prevBSP, prevSSP;
  19.    
  20.     // currBSP = current Bought State Profit
  21.     // currSSP = current Sold State Profit
  22.     int currBSP, currSSP;
  23.    
  24.     prevBSP = -v[0]; prevSSP = 0;
  25.    
  26.     for(int i = 1; i < n; i++) {
  27.         currBSP = max(prevBSP, prevSSP - v[i]);
  28.         currSSP = max(prevSSP, prevBSP + v[i] - fee);
  29.        
  30.         // updating values
  31.         prevBSP = currBSP;
  32.         prevSSP = currSSP;
  33.     }
  34.    
  35.     return prevSSP;
  36. }
  37.  
  38. int maxProfit(vector<int> &prices, int fee) {
  39.     vector<int> v = prices;
  40.     int n = v.size();
  41.    
  42.     return solve(v, n, fee);
  43. }
  44.  
  45. int main()
  46. {
  47.     ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  48.     srand(chrono::high_resolution_clock::now().time_since_epoch().count());
  49.  
  50.     // #ifndef ONLINE_JUDGE
  51.     //     freopen("input.txt", "r", stdin);
  52.     //     freopen("output.txt", "w", stdout);
  53.     // #endif
  54.  
  55.     vector<int> prices {1, 3, 2, 8, 4, 9};
  56.     int fee;
  57.     fee = 2;
  58.     cout << maxProfit(prices, fee);
  59.  
  60.     return 0;
  61. }
  62.  
  63. // Time complexity: O(n), where n = size of input array
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement