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

来源:互联网 发布:如何评价邓小平 知乎 编辑:程序博客网 时间:2024/05/16 12:24
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. 输入参数检查。