1007 Maximum Subsequence Sum (25)(25 分)
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
本例使用了C语言进行编写。
代码如下:
#include <stdio.h>
#include <malloc.h>
int MaxSubseqsum(int A[], int N);
int first,last;
int main()
{
int N,i,MaxSum;
int *A;
scanf("%d",&N);
MaxSum = 0;
A = (int*)malloc(N*sizeof(int));//动态赋予数组空间
for(i=0;i<N;i++){
scanf("%d",&A[i]);
}
first = 0; last = N - 1;//默认的始末位置
MaxSum = MaxSubseqsum(A,N);
printf("%d %d %d", MaxSum, A[first], A[last]);//输出的是最大子列和的值,以及这个子列开始和结尾的数字(而非索引
return 0;
}
int MaxSubseqsum(int A[], int N){
int ThisSum, MaxSum;
int i,temp;
ThisSum = 0; MaxSum = -1;
temp = 0;
for(i=0;i<N;i++){
ThisSum += A[i];
if(ThisSum>MaxSum){
MaxSum = ThisSum;
last = i;
first = temp;
}else if(ThisSum<0){//说明前面的值对后面的子列相加已经无效,舍弃
ThisSum = 0;
temp = i + 1;
}
}
if(MaxSum<0){//若MaxSum从未从ThisSum中得到过值,则将其化为0
MaxSum = 0;
}
return MaxSum;
}
其中最困惑我的一个问题就是我的测试5总是错误,原来我是用MaxSum == 0判断是否需要将first和last分别设为0和N-1的,百思不得其解下,我参考了其他人的代码,发现他们都是令MaxSum=-1,到最后通过判断是否MaxSum仍小于0来判断是否是全体负数的集合。
那么为什么MaxSum要设为负值呢?举例若-2 0这样一组数据,正常来说是0 0 0,若用MaxSum ==0来判断,再将first和last分别设为0和N-1的话,结果就变成了0 -2 0,不合题意了。