【leetcode】Maximum Subarray

时间:2024-08-23 16:07:50

Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

More practice:

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

在累加的过程中,如果发现sum<0则说明前面的序列对后面的序列没有贡献,故此时设置sum=0
 class Solution {
public:
int maxSubArray(int A[], int n) { int sum,maxSum;
sum=maxSum=A[];
for(int i=;i<n;i++)
{
if(sum<) sum=;
sum+=A[i]; if(maxSum<sum) maxSum=sum;
}
return maxSum;
}
};
采用分治法求解:
找到左半边最大的序列值,找到右半边最大的序列值,找到中间序列的值
 class Solution {
public:
int maxSubArray(int A[], int n) { divideAndConquer(A,,n-);
} int divideAndConquer(int A[],int left,int right)
{ if(left==right) return A[left]; int mid=(left+right)/; int leftMax=divideAndConquer(A,left,mid);
int rightMax=divideAndConquer(A,mid+,right); int midSum1=;
int midMax1=A[mid]; for(int i=mid;i>=left;i--)
{
midSum1+=A[i];
if(midMax1<midSum1) midMax1=midSum1;
} int midSum2=;
int midMax2=A[mid+]; for(int i=mid+;i<=right;i++)
{
midSum2+=A[i];
if(midMax2<midSum2) midMax2=midSum2;
} int midMax=midMax1+midMax2; return max(max(leftMax,rightMax),midMax); }
};