Maximum Subsequence Sum(C语言版)

Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence 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

关键之处:

这是那个最大子列和问题的改进,注意最后一句话:

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.

数列都为负数的时候,最大子列和定义为0,输出最后一个和最末一个数。

代码:

#include <stdio.h>
#define MAXN 10000
void MaxSubseqSum2 ( int A[], int N ); 
int main(void) {
	int K, i;
	int a[MAXN] = {0};
	
	scanf("%d", &K);
	for ( i = 0; i < K; i++ )
		scanf("%d", &a[i]);
	MaxSubseqSum2 ( a, K );
	
	return 0;
}

void MaxSubseqSum2 ( int A[], int N ) {
	int ThisSum, MaxSum = -1;
	int i, j, start, stop;
	
	for ( i = 0; i < N; i++ ) {    //i是子列的左端。
		ThisSum = 0;    
		for ( j = i; j < N; j++ ) {    //j是子列的右端。
			ThisSum += A[j];    //i相同,j不同时,每算一个子列只要再多添一项就够了。
			if ( ThisSum > MaxSum ) {    //若发现当前子列更大,更新它。
				MaxSum = ThisSum;
				start = A[i];    //标记子列从哪个数开始。
				stop = A[j];    //标记子列从哪个数结束。
			}
		}
	}
	if ( MaxSum < 0 )	printf("%d %d %d\n", 0, A[0], A[N-1]);    //全是负数的情况。
	else	printf("%d %d %d\n", MaxSum, start, stop);
}

猜你喜欢

转载自blog.csdn.net/YelloJesse/article/details/82313978