您的位置:首页 > 其它

写正确函数需要注意的地方:子数组的最大和

2012-08-20 11:27 211 查看
int maxSum(int* a, int count)
{
if(a==NULL)
{
cerr<<"array==NULL"<<endl;
throw ("array == NULL");
}
if(count<0)
{
cerr<<"count<0"<<endl;
throw ("count<0");
}

int max=0x80000000;
int from=0;
int sum=0;
for(int i=0;i<count;++i)
{
sum+=a[i];
if(sum<0)
{
from=i+1;
sum=0;
}
else if(sum>max)
{
max=sum;
}
}
return max;
}


 

1. 需要确认子串是否能够为空串。

2. 如果不能为空串,则max初始化为最小的int,也就是0x80000000;

3. 如果能够为空串,则max初始化为0.

4. 输入参数检查。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null
相关文章推荐