最大子数组

来源:互联网 发布:知乎 段子 编辑:程序博客网 时间:2024/06/03 21:33

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

 注意事项

子数组最少包含一个数

样例

给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

分析:子数组是指原数组中连续的一组数。求最大值,如果数组中元素都小于0;则直接返回数组的最大值。对于一般的情况。我们只要遍历求数组,

同时对其求和,如果和数变得小于0,那就说明了此时这个子数组是不符合题意的,如果和数为正且大于之前求和过程中记录的最大值,那就将这个

和数赋值给MAX,这样遍历一趟就将其中的最大和给求出来了。

class Solution {
public:
    /*
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    int maxSubArray(vector<int> &nums) {
        // write your code here
        int max=nums[0];
        for(int i=0;i<nums.size();i++)
        {
            if(max<nums[i])
            max=nums[i];
        }
        if(max<0)return max;
        int sum=0;
        max=0;
        for(int i=0;i<nums.size();i++)
        {
            sum+=nums[i];
            if(sum<0)sum=0;
            if(sum>max)
            max=sum;
        }
        return max;
    }
};

原创粉丝点击