数组中最大的子数组之和
一个有N个整数元素的一维数组(A[0]、A[1],...A[n-1]),求子数组之和的最大值。
例子:
[1, -2, 3, 5, -3, 2] 返回:8
[0, -2, 3, 5, -1, 2] 返回:9
[-9, -2, -3, -5, -3] 返回:-2
需要注意的是,如果考虑到数组首尾相连,则
1、先按不相连计算出最大值max
2、从尾往头扫描,找出最大值m1,并记录最大位置i,再从头往尾扫描,找出最大值m2, 并记录最大位置j,若i>j,则比较m1+m2与max,求出最大值,若i<=j,则令m = A[0]+A[1]+A[2]+...A[n-1],求出m和max之间的最大值。
int MaxSum4(int *A, int n,int &beg,int &end)
{
if(A==NULL||n<=1)
{
cout<<"error input"<<'\n';
exit(0);
}
if(n==1)
return A[0];
int pos = 0;
int CurSum = A[0];
int MaxSum = A[0];
for(int i = 1; i<n;++i)
{
if(CurSum<=0)
CurSum = 0;
CurSum += A[i];
if(CurSum>=MaxSum)
{
MaxSum = CurSum;
pos = i;
}
}
int pos1 = 0,max1 = A[0];
CurSum = A[0];
for(int i = 1;i<=n-1;++i)
{
CurSum += A[i];
if(CurSum>=max1)
{
max1 = CurSum;
pos1 = i;
}
}
CurSum = A[n-1];
int pos2 = n-1, max2 = A[n-1];
for(int j = n-2; j>=0; --j)
{
CurSum += A[j];
if(CurSum>=max2)
{
max2 = CurSum;
pos2 = j;
}
}
int sum = 0;
if(pos1>=pos2)
{
for(int i = 0; i<n; ++i)
sum+=A[i];
}
else
{
for(int i = 0; i<=pos1; ++i)
{
sum+=A[i];
}
for(int j = n-1; j>=pos2; --j)
{
sum+=A[j];
}
}
int temp = MaxSum>sum?MaxSum:sum;
if(MaxSum==temp)
{
end = pos;
while(temp!=0)
{
temp-=A[pos--];
}
beg = ++pos;
return MaxSum;
}
else
{
if(pos1>=pos2)
{
beg = 0;
end = n-1;
}
else
{
end = pos2;
beg = pos1;
}
return sum;
}
return MaxSum>sum?MaxSum:sum;
}