浙大数据结构慕课课后题(01-复杂度2 Maximum Subsequence Sum)

题目要求:

Given a sequence of K integers { N1​, N2​, ..., NK​ }. A continuous subsequence is defined to be { Ni​, Ni+1​, ..., Nj​ } where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence. 

输入格式 :

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space. 

输出格式 :

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). 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.

样例输入:

10
-10 1 2 3 4 -5 -23 3 7 -21

样例输出:

10 1 4 

题解: 

        思路如注释所示,可通过所有测试点。

#include<bits/stdc++.h>
using namespace std;
int a[100005]={0};
int n,front,rear;
int fast(){
	
	int desum = 0,zsum = 0; 
	for(int i=0;i<n;i++){
		cin>>a[i];
		if(a[i]<0) desum++;	    //记录负数数量 
		if(a[i]==0) zsum++;             //记录0的数量 
	}
	if(desum+zsum==n&&zsum!=0){
		cout<<'0'<<' '<<'0'<<' '<<'0';
		return 0;
	} 
	
	int max = 0,sum = 0,t=0;
	
	for(int i=0;i<n;i++){
		sum = sum+a[i];
		if(sum>max){
			max = sum;
			front = t;      //更新最大序列的首位置
			rear = i;       //更新最大序列的尾位置 
		}
	
		if(sum<0){
			sum = 0;
			t = i+1;
		} 	
	}
	if(desum!=n)	
	cout<<max<<' '<<a[front]<<' '<<a[rear];
	else
	cout<<'0'<<' '<<a[0]<<' '<<a[n-1];
    return 0;
} 
 
int main(){
	cin>>n;
 
    fast();	
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

        题目为英文,有道翻译后如下所示:

        这题的输出格式感觉有点奇怪,不知道是我理解问题还是翻译问题...提交后发现只有0和负数的那个测试点没过,按我的想法是应该输出第一个0的位置(就是假如说第一个0的数组下标为3,就应该输出0 3 3,意思是最大和为0,首尾位置都为3),跑了下别人的ac代码发现这种情况应该输出0 0 0(?) ,可能出题人想这样输出吧。

        这题用到了上一个题的在线处理方法,在此基础上记录最大子列和的首尾位置,如果有相同的则输出最小的下标号,我用的方法是只在最大值发生改变的时候更新一系列的值,所以后续相等的情况可以直接忽略,以达到目的。

        全负数的情况就按题目要求输出。

        我的这篇博客写了求最大子列和的三种常用方法,感兴趣的朋友可以转去。   浙大数据结构课后题(01-复杂度1 最大子列和问题)icon-default.png?t=N7T8https://blog.csdn.net/Charon_super/article/details/140288619?spm=1001.2014.3001.5501        此系列为作者记录数据结构学习文章,由于能力所限,难免有细节处理不当之处,恳请读者谅解并指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值