求最大子列和的几种方法:https://blog.csdn.net/he626shidizai/article/details/88378773
注意事项
写这道题的时候才意识到审题是多么的重要,最前面的分析错了,后面怎么都不会对的。改了好多次才成功,而且还只能打补丁。输出有很多需要注意的点:
- output the one with the smallest indices i and j (as shown by the sample case)----也就是说 如果子列是 0 0 1 2 3 的情况,那么子列的第一个元素是0而不是1
- If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.-----如果出现负数和0混在一起的情况,那么最大子列就是0的序列 如:-1 -1 0 输出的结果就应该是 0 0 0
代码
#include<stdio.h>
int main(){
int k;
scanf("%d",&k);
int *a = new int[k];
for(int i = 0; i < k; i ++)
scanf("%d",&a[i]);
int max_sum = -1; //当前最大子列和
int this_sum = 0; //当前子列和
int sub_left = 0; //当前子列的最左下标
int left = 0; //最大和子列的最左下标
int right = k-1; //最大和子列的最右下标
for(int i = 0;i < k; i ++){
this_sum += a[i];
if(this_sum > max_sum){
max_sum = this_sum;
left = sub_left;
right = i;
}
else if(this_sum < 0){
this_sum = 0;
sub_left = i + 1;
}
}
if(max_sum >= 0)
printf("%d %d %d",max_sum, a[left], a[right]);
else //全部是负数的情况
printf("%d %d %d",0, a[0], a[k-1]);
delete []a;
return 0;
}