LintCode-41.最大子数组

最大子数组

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

注意事项

子数组最少包含一个数

样例

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

挑战

要求时间复杂度为O(n)

标签

领英 子数组 贪心 枚举法 LintCode 版权所有 数组

code

class Solution {
public:
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
int maxSubArray(vector nums) {
// write your code here
int maxSub=0x80000000,accSub=0,size=nums.size();

if(size<=0)
return 0;

for(int i=0; i<size; i++) {
if(accSub < 0)
accSub = nums[i];
else
accSub+=nums[i];

if(accSub > maxSub)
maxSub = accSub;
}
return maxSub;
}
};

posted @ 2017-05-04 16:38  LiBaoquan  阅读(387)  评论(0)    收藏  举报