Advertisement
Fastrail08

Best Time to Buy & Sell Stocks 2 - Infinite Transactions

Jun 18th, 2025
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. /*
  6. QUESTION - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
  7. */
  8.  
  9. int getMaxProfitInfiniteTransaction(vector < int > & prices) {
  10.     int totalProfit = 0, minIdx = -1;
  11.    
  12.     for(int i = 0; i < prices.size(); i++){
  13.         //form a minimum OR capture a better minimum to buy
  14.         if(minIdx == -1 || prices[i] < prices[minIdx]){
  15.             minIdx = i;
  16.         }
  17.         //capture the best day to sell
  18.         else{
  19.             // if the next day has lower price than the current day, capture the buy - sell pair and make profit
  20.             if(i != prices.size() - 1 && prices[i + 1] < prices[i]){
  21.                 totalProfit += (prices[i] - prices[minIdx]);
  22.                 //reset the minIndex/buy day to -1, as we have already captured the profit for this buy, as we made a complete transaction by selling the share today
  23.                 minIdx = -1;
  24.             }
  25.             //handling for last index, capture only if a buy exists.
  26.             else if(i == prices.size() - 1){
  27.                 if(minIdx != -1){
  28.                     totalProfit += (prices[i] - prices[minIdx]);
  29.                 }
  30.             }
  31.         }
  32.     }
  33.     return totalProfit;
  34. }
  35.  
  36. int main() {
  37.     // your code goes here
  38.     int n;
  39.     cin >> n;
  40.     vector < int > prices(n);
  41.     for (int i = 0; i < n; i++) {
  42.         cin >> prices[i];
  43.     }
  44.     cout << getMaxProfitInfiniteTransaction(prices) << '\n';
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement