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.
#include <stdio.h>
void MaxSubseqSum2( int a[], int N);
int main(int argc,const char *argv[])
{
int k;
scanf("%d",&k);
int a[k];
for(int i=0;i<k;i++)
{
scanf("%d",&a[i]);
}
MaxSubseqSum2(a,sizeof(a)/sizeof(a[0]));
return 0;
}
void MaxSubseqSum2( int a[], int N)
{
int flag=0;
int *p1=a,*q1=&a[N-1];//定义指针用于指向最大子列和的左端和右端
int thissum=0,maxsum=-1;
for(int i=0;i<N;i++)
{
thissum=0;
for(int j=i;j<N;j++)
{
thissum+=a[j];
if(thissum>maxsum)
{
flag=1;
maxsum=thissum;
p1=&a[i];
q1=&a[j];
}
}
}
if(!flag)
{
printf("%d %d %d",0,*p1,*q1);
}else
{
printf("%d %d %d",maxsum,*p1,*q1);
}
}