Advertisement
vaibhav1906

Best Time to Buy and Sell Stock

Nov 16th, 2021
1,783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int maxProfit(vector<int>& prices) {
  4.        
  5.        //maxAtRight = {6,6,6,6,4,0} => currProfit = maxAtRight[i] - prices[i]
  6.        
  7.         int n = prices.size();
  8.        
  9.         vector<int> maxAtRight (n,0);
  10.         int curMax = prices[n-1];
  11.        
  12.         for(int i = n-2; i>=0; i--){
  13.            
  14.             maxAtRight[i] = curMax;
  15.            
  16.             curMax = max(curMax,prices[i]);
  17.            
  18.         }
  19.        
  20.        
  21.         int profit = 0;
  22.        
  23.         for(int i = 0; i<n-1; i++){
  24.             int curProfit = maxAtRight[i] - prices[i]; // If we buy on ith day, to get maximum profit, we have to sell on maximum value to right of it and which is maxAtRight
  25.            
  26.             if(curProfit>profit){
  27.                 profit = curProfit;
  28.             }
  29.            
  30.         }
  31.        
  32.         return profit;
  33.        
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement