码迷,mamicode.com
首页 > 其他好文 > 详细

5-1 Maximum Subsequence Sum (25分)

时间:2017-06-25 13:49:42      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:通过   sequence   har   sam   elements   element   reset   output   space   

Given a sequence of KK integers { N_1N?1??, N_2N?2??, ..., N_KN?K?? }. A continuous subsequence is defined to be { N_iN?i??, N_{i+1}N?i+1??, ..., N_jN?j?? } 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\n", 0, s[0], s[n-1]);
35     else  
36         printf("%d %d %d\n", maxSum, start, end);
37     return 0;
38 }

 

5-1 Maximum Subsequence Sum (25分)

标签:通过   sequence   har   sam   elements   element   reset   output   space   

原文地址:http://www.cnblogs.com/hello-lijj/p/7076613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!