66. Maximum Subarray 最大子序列和
问题描述
'难度:easy'
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.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…
中文:给定一串序列,返回其子序列和最大值。
思路:
从第一个元素开始依次遍历每个元素,并计算每个子序列的和,如果当前子序列和比上一子序列和小,则该序列和一定不是最大,直接跳过。
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
这里需要注意一点:子序列的长度>=1,即 一个元素的子序列也是子序列
// C++
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums.size()==0)
return 0;
int maxsum = nums[0];
for(int i=0;i<nums.size();i++)
{
int temp = nums[i];
maxsum = maxsum>temp?maxsum:temp;
for(int j =i+1;j<nums.size();j++)
{
temp = temp + nums[j];
maxsum = maxsum>temp?maxsum:temp;
}
}
return maxsum;
}
};