Share my cpp code, easy understand


  • 0
    K

    class Solution {

    public:

    int maxProfit(vector<int>& prices) {
        int profit = 0, pre = 0;
    
        for (int i = 1; i < prices.size();) {
            while (i < prices.size() && prices[i] <= prices[i - 1])
                i++;
            pre = i - 1;
            while (i < prices.size() && prices[i] > prices[i - 1]) 
                i++;
            profit += prices[i - 1] - prices[pre];
        }
        return profit;
    }
    

    };


Log in to reply
 

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