PAT数据结构_01-复杂度2 Maximum Subsequence Sum (25分)

题目:  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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值