Problem Description: Given a sequence a[1],a[2]...a[n], the maximum value of the elements in its contiguous subsequence is solved
For example: 6-1 5 4-7 The maximum contiguous subsequence of this sequence and 14
For specific questions see: Hdoj 1003 TZU 1202
This question is also described in the 13th page of the Chinese version of the data structure and algorithmic Analysis--c language description (Weiss) (page 18th of the English edition). An algorithmic program is given on page 21st:
int maxsubsequencesum (const int a[], int N) { int thissum,maxsum,j; thissum = maxsum = 0; for (j = 0; J < N; J + +) { thissum + = a[j]; if (Thissum > Maxsum) maxsum = thissum; else if (Thissum < 0) thissum = 0; } return maxsum; }
I wrote the algorithm in the following way:
int maxsubsequencesum (const int a[], int N) { int thissum,maxsum,j; Thissum =0, maxsum =int_min; for (j = 0; J < N; J + +) { thissum + = a[j]; if (Thissum > Maxsum) maxsum = thissum; if (Thissum < 0) thissum = 0; } return maxsum; }
You must delete the Else keyword at this point because it is caused by using a different value to initialize the variable. Examples in a book can always guarantee that maxsum are non-negative. And I rewrite the algorithm in many cases maxsum will be negative
My ACM program is as follows (all two sites above are AC):
#include <stdio.h> #include <limits.h> #define MAX 100000+100 int main (void) { int n ; int m; int A[max]; int i,j; int thissum,maxsum; int Maxstart,maxend,thisstart; scanf ("%d", &n); for (i = 1; I <= n; i++) { scanf ("%d", &m); for (maxstart=maxend=thisstart=thissum=0,maxsum=int_min,j = 0; j < m; j + +) { scanf ("%d", &a[j]); Thissum + = A[j]; if (Thissum > Maxsum) { maxsum = thissum; Maxstart = Thisstart; Maxend = j; } if (Thissum < 0) { thissum = 0; Thisstart = j+1; } } if (i > 1) printf ("\ n"); printf ("Case%d:\n", i); printf ("%d%d%d\n", maxsum,maxstart+1,maxend+1); } return 0; }
The main part of the program is also the above algorithm, just add the sub-sequence index number processing.