A naive cpp solution


  • 0
    C
    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int max = nums[0], sum = nums[0];
            for (int i = 1; i < nums.size(); i++) {
                if (sum <= 0 && nums[i] > sum) {
                    sum = nums[i];
                    if (sum > max) {
                        max = sum;
                    }
                } else if (sum > 0) {
                    sum += nums[i];
                    if (sum > max) {
                        max = sum;
                    }
                }
            }
            return max;
        }
    };

Log in to reply
 

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