Share my C++ solution,easy to understand


  • 0
    V
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int n = prices.size();
            if (n == 0 || n == 1)
                return 0;
                
            int profit = 0, i = 0, d = 0;
            
            for (i = 1; i < n; ++i)
            {
                d = prices[i] - prices[i - 1];
                if (d > 0)
                    profit += d;
            }
            
            return profit;
        }
    };

Log in to reply
 

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