# 053. Maximum Subarray

## 刷题内容

• https://leetcode.com/problems/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.

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


Ë¼Â·1 **- Ê±¼ä¸´ÔÓ¶È: O(lgn)- ¿Õ¼ä¸´ÔÓ¶È: O(1)***

class Solution {
public:
int findArray(vector<int>& nums,int beg,int en)
{
if(beg == en)
return nums[en];
int mid = (beg + en) / 2;
int temp = max(findArray(nums,beg,mid),findArray(nums,mid + 1,en));
int sum = 0,max1 = INT_MIN,max2 = INT_MIN;
for(int i = mid;i >= beg;--i)
{
sum += nums[i];
max1 = max(max1,sum);
}
sum = 0;
for(int i = mid + 1;i <= en;++i)
{
sum += nums[i];
max2 = max(max2,sum);
}
return max(temp,max1 + max2);
}
int maxSubArray(vector<int>& nums) {
return findArray(nums,0,nums.size() - 1);
}
};


Ë¼Â·2 **- Ê±¼ä¸´ÔÓ¶È: O(n)- ¿Õ¼ä¸´ÔÓ¶È: O(1)***

ÕâÀï»¹¿ÉÒÔÔÚO(n)µÄÊ±¼ä¸´ÔÓ¶ÈÇó½â£¬±éÀúÊý×é£¬Èôret > 0,ret =nums[i] ·ñÔòret += nums[i]

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int length = nums.size(),ret = nums[0],ans = nums[0];
for(int i = 1;i < length;++i)
{
if(ret <= 0)
ret = nums[i];
else
ret += nums[i];
ans = max(ans,ret);
}
return ans;
}
};


apachecn/AiLearning