Simple c++ 8ms solution


  • 3
    G
    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int sum = 0;
            int max = numeric_limits<int>::min();
            for(size_t i = 0; i < nums.size(); i++) {
                sum += nums[i];
                max = std::max(sum, max);
                sum = std::max(sum, 0);
            }
            
            return max;
        }
    };
    

    Whenever the sum is greater than max, replace max. Whenever sum is less than zero, reset sum to 0 since any number plus a negative number cannot exceed itself.


Log in to reply
 

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