zoukankan      html  css  js  c++  java
  • 5-1 Maximum Subsequence Sum (25分)

    Given a sequence of KK integers { N_1N1​​, N_2N2​​, ..., N_KNK​​ }. A continuous subsequence is defined to be { N_iNi​​, N_{i+1}Ni+1​​, ..., N_jNj​​ } where 1 le i le j le K1ijK. 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 KK (le 1000010000). The second line contains KK 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 ii and jj (as shown by the sample case). If all the KK 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




    --------------------------------------------------------------
    很无奈,最后测评只用23分,不知道哪个地方测试没通过
    --------------------------------------------------------------





     1 #include <stdio.h>
     2 
     3 int main(int argc, char const *argv[])
     4 {
     5     int n = 0, i, s[10000];
     6     int subSum = 0, maxSum = 0;
     7     int start, end, t;
     8     scanf("%d", &n);
     9     
    10     // input number
    11     for(i = 0; i < n; i++)
    12     {
    13         scanf("%d", &s[i]);
    14     }
    15 
    16     start = 0;
    17     for(i = 0; i < n; i++)
    18     {
    19         subSum += s[i];
    20         if(subSum < 0)
    21         {
    22             subSum = 0;
    23             t = i+1;
    24         }
    25         else if(subSum > maxSum)
    26         {
    27             maxSum = subSum;
    28             start = t;
    29             end = s[i];
    30         }
    31     }
    32 
    33     if(maxSum == 0)  //全部为负数
    34         printf("%d %d %d
    ", 0, s[0], s[n-1]);
    35     else  
    36         printf("%d %d %d
    ", maxSum, start, end);
    37     return 0;
    38 }
  • 相关阅读:
    Java8时间处理
    yii2.0上传图片
    将字符串不足长度的填充到指定长度
    通过PHPExcel将Excel表文件中数据导入数据库
    css万能清除原理
    浮动+清除浮动
    DIV滚动条设置添加 CSS滚动条显示与滚动条隐藏
    地图上显示点在点上标注当前点的id
    百度地图点击地址后显示图标,保存到数据库之后,页面显示的是保存的坐标图标
    百度地图API
  • 原文地址:https://www.cnblogs.com/hello-lijj/p/7076613.html
Copyright © 2011-2022 走看看