053. Maximum Subarray
难度Easy
刷题内容
原题连接
- 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.
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;
}
};