题目: https://pta.patest.cn/pta/test/1342/exam/4/question/18204
# include<iostream>
using namespace std;
int main(){
int N;
cin >> N;
int numSeq[10000];
for (int i = 0; i < N; ++i){
cin >> numSeq[i];
}
/*
// 连续最大和maxSum,获得的序列,起点为startPoint,连续字符长度为length (包含首位)
*/
int maxSum=-1, startPoint=0, length=0 ;
//设maxSum为-1,
//针对于“全是负数”,则maxSum不会被改变,maxSum=-1,即最后跳入else的输出cout。
//针对于“仅负数和零”,则(currSum>maxSum)会被触发,maxSum=0,最后跳入 (maxSum>=0) 的输出cout
int currSum = 0, currStart = 0, currLength = 0;
for(int i=0; i<N; i++){
currSum += numSeq[i];
currLength += 1;
//如果 当前子列和大于记录和, 或者 相等&& 当前长度小于记录indice长度,替换
// if(currSum>maxSum || (currSum==maxSum && currLength<length) ){
if(currSum>maxSum){
// In case that the maximum subsequence is not unique, output the one with the smallest indices ii and jj (as shown by the sample case). I
//对于相同值,取首先出现的那组
maxSum = currSum;
startPoint = currStart;
length = currLength;
// cout<<"maxSum"<<maxSum<<", startPoint "<<startPoint<<", length"<<length<<endl;
}
if(currSum<0){ //针对 “最大和前面有一段是0”,即 当 currSum>=0 需要把0计入最大和之中
currSum = 0;
currStart = i+1;
currLength = 0;
}
}
if(maxSum>=0){
cout<<maxSum<<" "<<numSeq[startPoint]<<" "<<numSeq[startPoint+length-1]<<endl; //等于0的情况不可包括于此
} else if(maxSum==-1){
cout<< 0 <<" "<<numSeq[0]<<" "<<numSeq[0+N-1]<<endl; //if(maxSum==-1)
}
return 0;
}