一个包含正整数和负整数的数组,找出和最大的子串.
Eg:int x[15] = {2,3,-5,5,6,-5,-1,14,9,-10,1,-1,75,4,-9};
给定一个整型数组a,求出最大连续子段之和
/*FindMaxSub.cpp
*by wangzhihong
*05/01/2007
***************
*specification: find the substring in an array which has the maximun sum
*/
#include <iostream>
using namespace std;
int FindMaxSub(int array[],int len,int &start,int &end)
{
int max,sum;
int i,temps;
start=end=temps=max=sum=0;
for(i=0;i<len;++i)
{
//there's no need to do this swap everytime when sum>max,
//because if array[i]>0 the sum will always increase
if(array[i]<0&&sum>max)
{
max=sum;
start=temps;
end=i-1;
}
//if the substring start from the next one,
//we should not add the whole prestring because its sum is minus
if(array[i]+sum<0)
{
sum=0;
temps=i+1;
continue;
}
sum+=array[i];
}
//if the last one is used,
//we should assign the max and end here
if(sum>max)
{
max=sum;
start=temps;
end=i-1;
}
return max;
}
int FindMaxSub2(int array[],int len,int &start,int &end)
{
int sum,max;
start=end=0;
max=sum=array[0];
for (int i=1;i<len;++i)
{
if(sum<=0 && summax) {
start=end=i;
max=sum;
}
} else {
sum+=array[i];
if(sum>max) {
end=i;
max=sum;
}
}
}
return max;
}
int main(void)
{
int *array;
int len,start,end;
int i;
cin>>len;
array=new int[len];
for(i=0;i<len;++i)
cin>>array[i];
cout<<"Max Subvalue: "<<FindMaxSub(array,len,start,end)<<endl;
cout<<"From: "<<start<<" To: "<<end<<endl;
delete[] array;
return 0;
}
来自其评论:http://blog.sina.com.cn/s/blog_4bd02c41010008ue.html