LeetCode No.53 Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

====================================================================================================================================

这道题的大意是:求出一个连续数组的连续子数组(不能为空)的最大和。

之前有做过类似这样类型的题目,不过有点区别就是那道题的子数组可以为空,只要每次更新当前连续子数组和、最大和即可。

class Solution {
public:
    int maxSubArray(vector& nums) {
        int n = nums.size () , maxer = 0 , currentsum = 0 ;
        for ( int i = 0 ; i < n ; i ++ )
        {
            currentsum = max ( 0 , currentsum + nums[i] ) ;
            maxer = max ( maxer , currentsum ) ;
        }
        return maxer ;
    }
};

leetcode这道题规定子数组不能为空,所以我们要对上面代码稍加修改。

class Solution {
public:
    int maxSubArray(vector& nums) {
        int n = nums.size () , maxer = nums[0] , currentsum = nums[0] ;
        for ( int i = 1 ; i < n ; i ++ )
        {
            currentsum = currentsum < 0 ? nums[i] : nums[i] + currentsum ;
            maxer = max ( maxer , currentsum ) ;
        }
        return maxer ;
    }
};



你可能感兴趣的:(leetcode,leetcode,C++,Maximum,Subarray)