LeetCode No.53 Maximum Subarray

来源:互联网 发布:ipad如何下载软件 编辑:程序博客网 时间:2024/05/16 23:34

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<int>& 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<int>& 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 ;    }};



0 0
原创粉丝点击