Very concise c++ solution,convert to the sum of the longest sub array problem


  • 1
    H
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if(prices.empty()) return 0;
            int maxSum=0;
            int sum=0;
            prices.push_back(INT_MIN+prices.back());
            for(int i=0;i<prices.size()-1;++i){
                sum+=prices[i+1]-prices[i];
                maxSum=max(maxSum,sum);
                sum=max(sum,0);
            }
            return maxSum;
        }
    };

Log in to reply
 

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