Share my C++ solution


  • 0
    V
    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int n = nums.size();
            if (n == 0) return INT_MIN;
            
            int largestSum = nums[0];
            int sum = nums[0], i = 1;
            
            while (i < n)
            {
                if (sum < 0)
                    sum = 0;
                sum += nums[i++];
                largestSum = max(largestSum, sum);
            }
            
            return largestSum;
        }
    };

Log in to reply
 

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