1. 程式人生 > >5-1 Maximum Subsequence Sum (25分)

5-1 Maximum Subsequence Sum (25分)

eth rst line input tin 無奈 ati scan scripts

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分)