您的位置:首页 > 其它

leetcode刷题 总结,记录,备注 53

2015-06-25 22:55 330 查看
leetcode刷题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
.
注意!这个题目与PAT上那个最大子列和有点区别,PAT上那个题是如果都为负数的话,最大和为0,这题并没有这样的提示,所以如果使用跟那题同样的线性时间的算法,需要在逻辑顺序上进行改动,先与最大的max比较,然后再进行与0的比较,进行置0,下面是代码
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int sum = *nums.begin(), cur = 0;
        vector<int>::iterator it;
        for (it = nums.begin(); it != nums.end(); ++it)
        {
            cur += *it;
            if (cur > sum)
            sum = cur;
            if (cur < 0)
            cur = 0;
        }
        
        return sum;
    }
};
额外要求里有更难的方法,,,暂且搁置。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: