(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;
}