Maximum continuous subsequence
Time Limit: 2000/1000 MS (Java/others) memory limit: 65536/32768 K (Java/Others)
Total submission (s): 19179 accepted submission (s): 8544
The Problem description is a sequence of {N1, N2,..., nk} Given K integers. Any continuous subsequence can be represented as {Ni, Ni + 1 ,...,
NJ}, where 1 <= I <= j <= K. The maximum continuous subsequence is the element and the largest of all consecutive subsequences,
For example, for a given sequence {-2, 11,-4, 13,-5,-2}, its maximum continuous subsequence is {11,-4, 13}, the largest and
Is 20.
In this year's data structure examination paper, the maximum sum of programming requirements is required. Now, a requirement is added, that is,
The first and last elements of the subsequence.
The input test input contains several test cases. Each test case occupies two rows, Row 1 provides a positive integer k (<1st), and row 3 provides K integers, separated by spaces. When K is 0, the input ends and the case is not processed.
For each test case, output the first and last elements of the largest sum and maximum continuous subsequences in one row.
, Separated by spaces. If the maximum continuous subsequence is not unique, the smallest sequence numbers I and j are output (for example, 2nd and 3 groups in the input sample ). If all k elements are negative, the maximum value is 0, and the first and last elements of the entire sequence are output.
Sample Input6-2 11-4 13-5-210-10 1 2 3 4-5-23 3 7-2165-8 3 2 5 01103-1-5-23-1 0- 20
Sample output20 11 1310 1 410 3 510 10 100-1-20 0 0
HintHinthuge input, scanf is recommended.
Source Zhejiang University Computer postgraduate review computer examination-2005
Recommendjgshining
State: F [I]: the longest continuous sequence state transition ending with I: F [I] = max {f [I-1] + A [I], A [I]} initial state: F [1] = A [I] requires the maximum value. You only need to find the maximum value from F [].
1 #include<stdio.h> 2 #include<string.h> 3 4 int a[10000],sum[10000],len[10000]; 5 6 int main() 7 { 8 freopen("ACM.txt","r",stdin); 9 int n;10 while(scanf("%d",&n)!=EOF) 11 { 12 if(n==0) break; 13 int i; 14 for(i=0;i<n;i++) scanf("%d",&a[i]); 15 sum[0]=a[0]; 16 len[0]=1; 17 int maxsum=sum[0],id=0;18 for(i=1;i<n;i++)19 { 20 if(sum[i-1]>0) 21 {22 sum[i]=sum[i-1]+a[i];23 len[i]=len[i-1]+1;24 } 25 else 26 { 27 sum[i]=a[i]; 28 len[i]=1; 29 } 30 if(sum[i]>maxsum) 31 { 32 maxsum=sum[i]; 33 id=i; 34 } 35 }36 if(maxsum<0) printf("0 %d %d",a[0],a[n-1]);37 else printf("%d %d %d",maxsum,a[id-len[id]+1],a[id]); 38 printf("\n");39 }40 return 0;41 }
View code
Maximum continuous subsequence