1007. Maximum Subsequence Sum (25)
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 -21Sample Output:
10 1 4
动态规划的经典问题,最大连续子序列和。
代码
2
3 int main()
4 {
5 int K;
6 int data[10000];
7 int i;
8 int flag;
9 while(scanf("%d",&K) != EOF){
10 flag = 0;
11 for (i=0;i<K;++i){
12 scanf("%d",&data[i]);
13 if(data[i] >= 0)
14 flag = 1;
15 }
16 if(flag == 0){
17 printf("0 %d %d ",data[0],data[K-1]);
18 continue;
19 }
20 int max_seq = data[0];
21 int max_s = 0,max_e = 0;
22 int sum = data[0];
23 int sum_s = 0,sum_e = 0;
24 for(i=1;i<K;++i){
25 if(sum < 0){
26 sum = data[i];
27 sum_s = sum_e = i;
28 }
29 else{
30 sum += data[i];
31 sum_e = i;
32 }
33 if(sum > max_seq){
34 max_seq = sum;
35 max_s = sum_s;
36 max_e = sum_e;
37 }
38 }
39 printf("%d %d %d ",max_seq,data[max_s],data[max_e]);
40 }
41 return 0;
42 }