LeeCode from 0 ——53. Maximum Subarray

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.

解题思路:
累加值最大的数组肯定以正数开头以正数结尾,且要使数组累加结果变大,则在累加的中间过程中不能出现累加结果小于0的情况。
1)将数组里面的数循环累加;
2)累加结果若是大于当前值则将最大值更新为累加结果;
3)累加结果若是小于0,则抛弃当前累加结果,将累加结果重新设置为0。
c++代码如下:
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n=nums.size();
        int sum=nums[0]>0 ? nums[0]:0;
        int maxsum=nums[0];
        for(int i=1;i<n;i++){
            sum=sum+nums[i];
            if(sum>maxsum)
                maxsum=sum;
            if(sum<0)
                sum=0;
        }
        return maxsum;
    }
};

猜你喜欢

转载自www.cnblogs.com/ssml/p/9212211.html