• 1007. Maximum Subsequence Sum (25)


    题目连接:https://www.patest.cn/contests/pat-a-practise/1007

    原题如下:

    Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } 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是直接将当前子列和置为0(因为负数不会将子列和增加)
    ,然后更改变量S的值,以供当出现下一个较大的子列和的时候更新Start和End的值。
     1 #include<stdio.h>
     2 #define Max 10001
     3 int main()
     4 {
     5     int K,i,j,Seq[Max];
     6     int MaxSeq=-1,sum=0;
     7     int start,end,S;
     8     scanf("%d",&K);
     9     for (i=0;i<K;i++)
    10     {
    11         scanf("%d",&Seq[i]);
    12     }
    13     start=end=S=Seq[0];
    14     for (i=0;i<K;i++)
    15     {
    16         sum+=Seq[i];
    17         if (sum>MaxSeq)
    18         {
    19             start=S;
    20             end=Seq[i];
    21             MaxSeq=sum;
    22         }
    23         else if (sum<0)
    24         {
    25             sum=0;
    26             S=Seq[i+1];
    27         }
    28     }
    29     if (MaxSeq==-1)
    30     {
    31         start=Seq[0];
    32         end=Seq[K-1];
    33         MaxSeq=0;
    34     }
    35 
    36     printf("%d %d %d",MaxSeq,start,end);
    37     return 0;
    38 }

  • 相关阅读:
    移动端开发常见的坑
    javascript的原始类型(primitive type)之间的关系。
    微信小程序学习:开发注意点
    canvas学习(一):线条,图像变换和状态保存
    css模仿微信弹出菜单
    html5 canvas绘制环形进度条,环形渐变色仪表图
    vue学习笔记(三):vue-cli脚手架搭建
    nodejs基础学习
    css3美化radio样式
    基于angular+bower+glup的webapp
  • 原文地址:https://www.cnblogs.com/wuxiaotianC/p/6347865.html
Copyright © 2020-2023  润新知