关闭

文章标题

9人阅读 评论(0) 收藏 举报
分类:

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

#include <stdio.h>
int main(){
    int a[10000],i=0,top=0,sum=0,h,r,t,z=1,l,x=1;
    int k,k1;
    scanf("%d",&k);
    k1=k;
    while(k1){
        scanf("%d",&a[i]);
        i++;
        k1--;
     }
    h=r=t=0;
    l=a[0];
    for(i=0;i<k;i++){
    if(a[i]>0) {
        z=0;
    }
//  else if(i>0){
//      if(a[i]>l){
//          l=a[i];
//      }
//  }
    if(a[i]==0) x=0;
        sum+=a[i];
        if(sum<0){
            sum=0;
            t=i+1;      
        }

        if(sum>top) {
            top=sum; 
            r=i;
            if(t!=h){
                h=t;
            }
        }
    } 
    if(z){
        switch(x){
            case 1:
                top=0;
                h=0;
                r=k-1;
                break;
            case 0:
                top=0;
                a[h]=0;
                a[r]=0;
        }
    }
    printf("%d %d %d",top,a[h],a[r]); 
    return 0;
} 

一开始没考虑到如果全为负数怎么处理
于是加入z=1用于判断是否有大于零的数

    if(a[i]>0) {
        z=0;
    }else if(i>0){
        if(a[i]>l){
            l=a[i];
        }

结果读题不仔细,全为0时的输出要求完全不一样,l的数据记录也没有意义。
x是再后来加的,用于0和负数混合输入的情况

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21次
    • 积分:12
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档