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 }
  • 相关阅读:
    图像轮廓提取
    图像分割学习
    数据的平面拟合 Plane Fitting
    目标跟踪_MeanShift
    灰度图像伪彩色
    OpenCv SGBM算法源码解读
    图像处理之滤波器
    Ubuntu下Jenkins(docker)配置Docker远程启动
    使用dockerfile文件创建镜像时docker build没有反应
    创建jdk8基础镜像
  • 原文地址:https://www.cnblogs.com/hello-lijj/p/7076613.html
Copyright © 2011-2022 走看看