求最大子数组的和
张纯,黄思思
#include<iostream.h>
int sum(int *a,int s,int
f)
{
if(s>f)
return 0;
int sum=0;
for(int
i=s;i<=f;i++)
{
sum=sum+a[i];
}
return sum;
}
int
main()
{
int n;
cout<<"please input the number of
array:"<<endl;
cin>>n;
int *a=new int[n];
int *b=new
int[n];
int *c=new int[n];
int p=0;
cout<<"please input the
array:"<<endl;
for(int
i=0;i<n;i++)
{
cin>>a[i];
}
int k=0;
int
l=0;
for(int
j=0;j<n;j++)
{
if(j==0&&a[j]>0)
{
b[k]=j;
k++;
}
else
if(j!=0&&a[j]>0&&a[j-1]<=0)
{
b[k]=j;
k++;
}
if(j==(n-1)&&a[j]>0)
{
c[l]=j;
l++;
}
else
if(j!=(n-1)&&a[j]>0&&a[j+1]<=0)
{
c[l]=j;
l++;
}
}
int
max=sum(a,b[0],c[0]),S=b[0],F=c[0];
for(int
s=0;s<k;s++)
{
for(int f=0;f<l;f++)
{
if(b[s]<c[f]&&max<=sum(a,b[s],c[f]))
{
S=b[s];
F=c[f];
max=sum(a,b[s],c[f]);
}
}
}
cout<<"the index of front
is:"<<S<<endl<<"the index of tail
is:"<<F<<endl;
cout<<"the Max of the stuArrray
is:"<<max<<endl;
return 0;
}
原文:http://www.cnblogs.com/hsslove/p/3611141.html