最大子列和问题

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.

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
题目来源于浙大PAT网站。
首先考虑最大子列和的问题。从头开始,一个数一个数求和,当 ThisSum > MaxSum 时,更新MaxSum的值。当ThisSum小于零时,ThisSum归零。这样可以求出最大子列和。进一步,我们输出最大子列的首末项。因为是采用for循环来计算最大子列和,所以,当Max更新时,for循环里面的i等于最大子列和的末项。用一个变量count记录,每次试图求解子列和所累加的项数(ThisSum清零时,count清零)。这样right - count 得到left。就能输出首末项了。而且很好的解决了出现重复子列的情况,选取下标小的子列,满足了题目要求。
但是,有一个很严重的问题就是负数和零。根据题目定义,当全为负数时,输出整个序列的首末项。我们上面说的算法,没有办法区分 全为负数 与 一堆负数夹杂零 这两种情况(一堆负数+零应该输出0 0 0)。我加入了一个zero变量来区分这两种情况。可以完成题目的要求。但是,如果题目改成输出最大子列首末项的 下标。我的算法还存在一定的bug,负数+零序列之中 重复子列和(都为零时,我的算法会输出大的下标); 多个零连续。这两个问题还不能解决。无奈要写作业去了,感觉学习编程的过程还是很有乐趣的!!就是课业繁重啊,加油。代码如下:
#include <stdio.h>
void Maxseq(int A[], int k){
	int ThisSum = 0, MaxSum = 0;
	int i, count = 0, flag = 0, left, right, zero = 0;
	for(i=0; i<k; i++){
		if(A[i] == 0){
			zero++;
			flag = i;
		}
		ThisSum += A[i];
		if(ThisSum > MaxSum){
		    MaxSum = ThisSum;
		    right = i;
		    left = right - count;
		}else if(MaxSum == 0 && A[i] == 0){
			right = i;
			left = right - count;
				if(ThisSum < 0){
		    ThisSum = 0; 
			count = -1;
	    }
	    count++;
	}
	if(MaxSum == 0 && zero == 0){
		left = 0;
		right = k-1;
	}


	printf("%d %d %d\n", MaxSum, A[left], A[right]); 
}
int main () {
	int k, i;
	scanf("%d", &k);
	int A[k];
	for(i=0; i<k; i++){
		scanf("%d", &A[i]);
	}
	Maxseq(A, k);
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值