• 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 }
  • 相关阅读:
    android内存知识普及抱怨墨迹内存大的同学看过来
    ICS 截屏(Screenshot)代码流程小结
    ICS Overlay主要流程
    Android中的sp和wp指针
    Android Display buffer_handle_t的定义
    adb shell input 命令
    百度地图API之MyLocationOverlay的使用(Android)
    由Android系统智能手机解锁图案引出的排列组合问题
    <script runat=server>、<%%>和<%#%>前台是服务器方法
    Oracle 日期运算 集合
  • 原文地址:https://www.cnblogs.com/hello-lijj/p/7076613.html
Copyright © 2020-2023  润新知