难度Easy
原题连接
内容描述
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.
思路1 - 时间复杂度: O(lgn)- 空间复杂度: O(1)*****
如果用暴力的方法去解,大部分人都会想到,这里我们可以对算法进行优化,这里我们用分治法的思想,把数组对半分为两个子数组,接着数组的最大值可能在[left,mid]区间,[mid + 1,right]区间或者在横跨mid的区间内,只要取这三个区间的最大值即可。
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;
}
};