#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
typedef struct{
int s;
int e;
int sum;
}seq;
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n,i,num[10010];
scanf("%d",&n);
seq max;
max.sum = 0;
int curSum = 0;
int start = 0,end;
for(i=0;i<n;i++){
int input;
scanf("%d",&input);
num[i] = input;
if(input<0){
if(curSum > max.sum){
max.sum = curSum;
max.s = start;
max.e = end;
}
if(curSum + input>0){
curSum += input;
end = i;
}else{
curSum = 0;
start = i+1;
}
continue;
}
else{
end = i;
curSum += input;
}
}
//如果最后一个是正数,又得检查一次
if(curSum > max.sum){
max.sum = curSum;
max.s = start;
max.e = end;
}
if(max.sum == 0){
max.s = 0;
max.e = n-1;
}
printf("%d %d %d",max.sum,num[max.s],num[max.e]);
return 0;
}
1,漏了这种情况: 3 4 0 应该输出 7 3 4, 那个0不能包含进最小序列
2,,题干中: 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的情况,如-1 0 0 -1应该输出0 0 0
正确代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
typedef struct{
int s;
int e;
int sum;
}seq;
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n,i,num[10010];
scanf("%d",&n);
seq max;
max.sum = 0;
int curSum = 0;
int start = 0,end;
int firstZeroFlag = 0;
for(i=0;i<n;i++){
int input;
scanf("%d",&input);
num[i] = input;
if(input<0){
if(curSum > max.sum){
max.sum = curSum;
max.s = start;
max.e = end;
}
if(curSum + input>0){
curSum += input;
end = i;
}else{
curSum = 0;
start = i+1;
}
}
else if(input>0){
end = i;
curSum += input;
}
//input如果为0,什么都不用做,除非这种情况:-1 0 0 -1
else if(input ==0 && !firstZeroFlag){
firstZeroFlag = 1;
}
}
//如果最后一个是正数,又得检查一次
if(curSum > max.sum){
max.sum = curSum;
max.s = start;
max.e = end;
}
if(max.sum > 0){
printf("%d %d %d",max.sum,num[max.s],num[max.e]);
}
//全是负数
else if(max.sum == 0 && firstZeroFlag == 0){
printf("0 %d %d",num[0],num[n-1]);
}
//有0存在,其余全是负数
else if(max.sum == 0 && firstZeroFlag == 1){
printf("0 0 0");
}
return 0;
}