1. 程式人生 > >1007. Maximum Subsequence Sum (25)

1007. Maximum Subsequence Sum (25)

all stdio.h sed separate tdi int clas urn -s

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,並且輸出首尾元素。
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 int num[10001];
 5 int main()
 6 {
 7     int n,flag=0; 
 8     int i;
 9     int sum=0,msum=-1,first=0,last=0,tempfirst=0;  //系列和,最大子系列和,首位,末位,暫時首位
10     scanf("%d",&n);
11     for( i=0; i<n; i++)
12     {
13         scanf("%d",&num[i]);
14         if( num[i]>=0)  //flag處理全為負數情況
15             flag=1;
16     }
17     if( !flag) //全為負數和為1
18         printf("0 %d %d",num[0],num[n-1]);
19     else
20     {
21         for( i=0; i<n; i++)
22         {
23             sum += num[i];
24             if( sum>msum)
25             {
26                 msum = sum;
27                 first = tempfirst;
28                 last = i;
29             }
30             else if( sum<0 )
31             {
32                 sum=0;
33                 tempfirst = i+1;
34             }
35         }
36         printf("%d %d %d",msum,num[first],num[last]);
37     }
38     return 0;
39 }

1007. Maximum Subsequence Sum (25)