数据结构 Maximum Subsequence Sum

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

 

8个测试点:

测试点 提示

0

sample换1个数字。有正负,负数开头结尾,有并列最大和
1 最大和序列中有负数
2

并列和对应相同i但是不同j,即尾是0

3 1个正数
4 全是负数
5 负数和0
6 最大和前面有一段是0
7 最大N

思路:

题看是看不懂的,最后只能靠翻译过活……

题目是找出最大子列和,以及它的第一个数和最后一个数。

设一个当前子列和sum,当sum<0时,它再加任何的数都不会大于 直接从下一个数字开始重新计算的 子列和,所以这道题的最主要判断条件为sum是否小于0

①题中对于整个数列所有元素都小于0时有规定特殊的输出,

即:("0 %d %d",数列第一个数,数列最后一个数)

但是依然要在过程中保存MaxSum为负数(该是什么是什么,不要画蛇添足):因为可能出现最大数是0的情况,导致无法区分。

②只需要多记录一个当前子列首位下标就可以,最后一个下标可以在 判断是否为当前最大子列和 之后选择性地记录。

③最好提前给设下的子列首尾下标赋初值,不然整个数列只有一个数时,那两个变量可能会为空,输出奇怪的数。

完整过程:

#include 
main()
{
    int N;
    scanf("%d",&N);
    int term[N];
    getTerm(term,N);
    getSum(term,N);
}
void getTerm(int *term , int N)
{
    int i,x;
    for(i=0;iMaxSum)
        {
            begin=exbegin;
            end=i;
            MaxSum=sum;
        }

    }
    if(MaxSum<0)
        printf("0 %d %d",term[0],term[N-1]);
    else
        printf("%d %d %d",MaxSum,begin,end);
    return 0;
}

 

你可能感兴趣的:(数据结构)