zoukankan      html  css  js  c++  java
  • Max Sum

    Problem Description
    Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
     
    Input
    The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
     
    Output
    For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
     
    Sample Input
    2
    5 6 -1 5 4 -7
    7 0 6 -1 1 -6 7 -5
     
    Sample Output
    Case 1:
    14 1 4
     
     
    Case 2:
    7 1 6
     
     1 #include <stdio.h>
     2 
     3 int main(){
     4     int T;
     5     int n;
     6     int number[100001];
     7     int i;
     8     int sum;
     9     int max;
    10     int start;
    11     int end;
    12     int time;
    13     int temp;
    14 
    15     
    16     scanf("%d",&T);
    17     time=1;
    18 
    19     while(T--){
    20         sum=0;
    21         max=-1000;
    22         start=0;
    23         end=0;
    24         temp=0;
    25 
    26         scanf("%d",&n);
    27 
    28         for(i=0;i<n;i++)
    29             scanf("%d",&number[i]);
    30 
    31         for(i=0;i<n;i++){
    32             sum+=number[i];
    33 
    34             if(sum>max){
    35                 max=sum;
    36                 start=temp;
    37                 end=i;
    38             }
    39 
    40             if(sum<0){   //关键是这里,当求和小于0时,便把下一个数值作为开头再找最大值
    41                 sum=0;
    42                 temp=i+1;
    43             }
    44         }
    45 
    46         printf("Case %d:
    ",time);
    47         time++;
    48         printf("%d %d %d
    ",max,start+1,end+1);
    49         if(T!=0)
    50             printf("
    ");
    51     }
    52 
    53     return 0;
    54 }
  • 相关阅读:
    mongodb.open失效导致访问地址404
    使用Express创建一个简单的示例
    CommonJs的模块规范
    javascript递归
    python入门简书2
    Python入门小白
    场景图层介绍
    在三维地图上改变相机的左右和上下视图
    显示/隐藏地面高程
    给要素图层添加信息窗口
  • 原文地址:https://www.cnblogs.com/zqxLonely/p/4062348.html
Copyright © 2011-2022 走看看