53. Maximum Subarray


Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

算法的复杂度为O(n),思路主要是这样的用一个max数组存储接下来可能是最大的数的值,从头开始遍历,当找到一个正数才开始加,如果找到负数,那么先把这个数存到max中,如果加上这个负数小于0,就开始下一次查找,Max=0,如果大于0,就加上这个数。

class Solution {

public:
    int maxSubArray(vector& nums) 
    {
        vector max;
        int Max=0;
        for(int i=0;i=0)
            {
                Max+=nums[i];
            }
            else if(nums[i]<0)
            {
                if(Max>0)
                {
                    max.push_back(Max);
                    if(Max+nums[i]>0)
                    {
                       Max+=nums[i];
                    }
                    else
                    {
                         Max=0;
                    }
                }
            }
        }
        max.push_back(Max);
        sort(max.begin(),max.end());
        sort(nums.begin(),nums.end());
        int res=max[max.size()-1];
        int re=nums[nums.size()-1];
        if(res<=0&&re<0)
        {
            return nums[nums.size()-1];
        }
        else
        {
            return max[max.size()-1];
        }
        
    }
};


你可能感兴趣的:(动态规划)