Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int maxProfit(vector<int>& prices) {
- //maxAtRight = {6,6,6,6,4,0} => currProfit = maxAtRight[i] - prices[i]
- int n = prices.size();
- vector<int> maxAtRight (n,0);
- int curMax = prices[n-1];
- for(int i = n-2; i>=0; i--){
- maxAtRight[i] = curMax;
- curMax = max(curMax,prices[i]);
- }
- int profit = 0;
- for(int i = 0; i<n-1; i++){
- 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
- if(curProfit>profit){
- profit = curProfit;
- }
- }
- return profit;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement