LeedCode-Easy-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.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
翻译一下大意:
就是给你一组数,要你求出最大的连续序列和.
思路如下
在线处理,就是每次给的数,用一个temp来记录加起来的和,如果和是负的,就丢掉,
重新记录
代码如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max=nums[0],temp=0;
for(int i=0;i<nums.size();++i){
temp+=nums[i];
if(temp>max){
max=temp;
}
if(temp<0){
temp=0;
}
}
return max;
}
};

浙公网安备 33010602011771号