Use 2 pointers to simulate buy and sell, O(n) 6ms


  • 0
    J

    class Solution {
    public:
    int maxProfit(vector<int>& prices) {
    int buy=0,sell=0;
    int profit=0;
    int n=prices.size();
    prices.push_back(INT_MIN);
    while(sell<n){
    if(prices[buy]>prices[buy+1]&&buy==sell){buy++;sell++;}
    else if(prices[buy]<=prices[buy+1]&&buy==sell){sell++;}
    else if(prices[sell]>prices[sell+1]){profit=profit+prices[sell]-prices[buy];buy=sell;}
    else if(prices[sell]<=prices[sell+1]){sell++;}
    }
    return profit;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.