浙大数据结构Maximum Subsequence Sum最大子列和2

01-复杂度2 Maximum Subsequence Sum (25分)

Given a sequence of K integers { N​1 , N​2, …, N​K}.Acontinuoussubsequence is defined to be { N​i​, N​i+1, …, N​j} 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.

Input Specification:
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.

Output Specification:
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.

Sample Input:

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

Sample Output:

10 1 4

题目有点坑啊,我写完以后一直有一个错误:并列和对应相同i但是不同j,即尾是0。
改了好久才改出来。原来是序列前0的情况,要从0开始算起,因为要求的是最小的 i 和 j 。

出现这个问题的可以用这几个例子验证:

输入:-1 -2 -3 0 -5
输入:0 0 0

输入:0 1 2 3
输出:6 0 3

输入:-2 0 0 1 0
输出:1 0 1

AC代码:

#include <iostream>
using namespace std;

int main() {
	int k;
	cin >> k;
	int Num[k];
	 
	int flag = 1 ,min = 0;	
	for (int i = 0; i < k; i++) {     
		cin >> Num[i];
		if (Num[i] >= 0) flag = 0;
		else if (Num[i] < 0) min += Num[i];  //所以负相加得到一个最小的值
	}
	if (flag) {			//全是负数
		cout << '0' << ' ' << Num[0] << ' ' << Num[k-1];
		return 0;
	}
	
	int sum = 0, max = min;  
	//重点在于给max一个在序列中最小的初值,在序列中遇到负数,rear和front也会继续随前进,直到遇到0或正数。
	int rear = 0, front = 0, temp = 0;
	for (int i = 0; i < k; i++) {
		sum += Num[i];
		if (sum > max)  {	//找到更大的值,重新赋值一下
			rear = i;
			front = temp;
			max = sum;
		}
		if (sum < 0) {		//负值直接去掉
			temp = i + 1;
			sum = 0;
		} 
	}
    cout << max << ' ' << Num[front] << ' ' << Num[rear];
	return 0;
}

在线处理法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值