Advertisement
Fastrail08

Best Time to Buy & Sell Stock - 1 Transaction

Jun 18th, 2025
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 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/
  7. */
  8.  
  9. int getMaxProfitOneTransaction(vector < int > & prices) {
  10.     int min = -1, maxProfit = 0;
  11.     for (int i = 0; i < prices.size(); i++) {
  12.         //set a minimum to buy on that day
  13.         if (min == -1 || prices[min] > prices[i]) {
  14.             min = i;
  15.         }
  16.         //repeatitvely capture the max profit you can make with the current minimum
  17.         else {
  18.             maxProfit = max(maxProfit, prices[i] - prices[min]);
  19.         }
  20.     }
  21.     return maxProfit;
  22. }
  23.  
  24. int main() {
  25.     // your code goes here
  26.     int n;
  27.     cin >> n;
  28.     vector < int > prices(n);
  29.     for (int i = 0; i < n; i++) {
  30.         cin >> prices[i];
  31.     }
  32.     cout << getMaxProfitOneTransaction(prices) << '\n';
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement