【PAT】Maximum Subsequence Sum-最大子序列

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

解析

这个问题很好理解,可以拆分为两个部分:求一组整数序列的最大子序列,并列出这个子序列中首尾两个数字。
根据题目要求,我们能够知道以下两点:

  • 如果有多个最大子序列,则输出第一个子序列的首尾两个数字。
  • 如果所有元素为负,最大子序列为0,输出原序列首尾两个数。

解题过程

  • 使用在线处理算法来找出最大子序列的值
  • 找出最大子序列最右侧处于原序列的位置,并通过位移来判定左侧边界位置
  • 针对全为0,全为负数,有0有负数的特殊序列进行针对性处理

示例代码

#include <stdio.h>

int main(){
    int ThisSum,MaxSum,MaxSum_t;
    int k=0,j=0;
    int Size;
    int Left,Right;//截至位置
    scanf("%d",&Size);
    int Sequence[Size];
    for( int i=0; i<Size; i++){
        scanf("%d", &Sequence[i]);
    }
    Left = Right = 0;
    MaxSum = ThisSum = MaxSum_t = 0;
    int count = 0;
    for( int i=0; i<Size; i++){
        ThisSum += Sequence[i];
        count++;
        if( ThisSum > MaxSum_t){
            MaxSum_t = ThisSum;
            if(MaxSum_t > MaxSum){
                MaxSum = MaxSum_t;
                Right = i;
                Left = Right - count;
            }
        }
        else if(ThisSum < 0){
            ThisSum = 0;
            MaxSum_t = 0;
            count = 0;
        }
    }
    int NegSum = 0;
    int ZeroSum = 0;
    for( int i=0; i<Size; i++){
        if( Sequence[i] < 0) NegSum++;
        if( Sequence[i] == 0) ZeroSum++;
    }


    if(NegSum == Size)
        printf("0 %d %d", Sequence[0], Sequence[Size-1]);
    else if(NegSum + ZeroSum == Size)
        printf("0 0 0");
    else
        printf("%d %d %d", MaxSum, Sequence[Left+1], Sequence[Right]);

   // printf("\nl=%d r=%d", Left, Right);

return 0;}

运行结果

这里写图片描述

我的微信公众号

猜你喜欢

转载自blog.csdn.net/sd4567855/article/details/80260986