PAT-A1007 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,开始、结尾为序列开始、结尾的数字。

解题思路

  1. 建立结构体存储子序列;
  2. 遍历给定序列,依次求出连续子序列和,如果连续子序列和比当前最大连续子序列和更大,则更新连续子序列和;当前连续子序列和小于0时舍去,从下个位置开始重新选定连续子序列;
  3. 遍历完成时输出当前最大连续子序列和并返回0值。

代码

#include<stdio.h>

struct SEQ{
    int begin;
    int end;
    int sum;
}temp,max;

void init(){
    max.sum=-1;
    temp.begin=-1;
    temp.sum=-1;
    return;
}
 
int main(){
    int K,num;
    int i;
    int first,last;
    scanf("%d",&K);//读入K 
    init();
    for(i=0;i<K;i++){
        scanf("%d",&num);
        if(i==0){
            first=num;
        }
        if(i==(K-1)){
            last=num;
        }
        if(temp.sum>=0){//到目前部分和仍大于0 
            temp.end=num;
            temp.sum+=num;
            if(temp.sum>max.sum){
                max=temp;
            }
        }else{
            temp.begin=num;
            temp.end=num;
            temp.sum=num;
            if(temp.sum>max.sum){
                max=temp;
            }
        }
    }
    if(max.sum==-1){
        max.begin=first;
        max.end=last;
        max.sum=0;
    }
    printf("%d %d %d\n",max.sum,max.begin,max.end);
    return 0;
}

运行结果

PAT-A1007 Maximum Subsequence Sum 题目内容及题解