1007. Maximum Subsequence Sum (25)
题意简单,寻找最大字串和。
算法:类似于暴力法,简单易懂。时间复杂度O(n^2),一直担心超时,结果通过了……
注意特殊case:
如,输入的是:
4
-1 0 0 -1
那么我们输出的应该是: 0 0 0
# include <stdio.h>
# include <stdlib.h>
typedef struct Max
{
int first;
int last;
int sum;
}Max;
int cmp(const void *a,const void *b)
{
return (*(Max*)b).sum - (*(Max*)a).sum;
}
int main()
{
Max max[10000];
int k, he, i, j;
int r[10000];
scanf("%d",&k);
for(i = 0; i < k; i ++)
{
scanf("%d",&r[i]);
}
for(i = 0; i < k; i ++)
{
max[i].first = r[i];
max[i].sum = -1;//之所以 sum 赋值-1,防止最大和为0
if(r[i] < 0)
{
continue;
}
he = 0;
for(j = i; j < k; j ++)
{
he += r[j];
//In case that the maximum subsequence is not unique,
//output the one with the smallest indices i and j .
if(he > max[i].sum)
{
max[i].sum = he;
max[i].last = r[j];
}
}
}
qsort(max,k,sizeof(struct Max),cmp);
if(max[0].sum == -1)//数列全负值
{
printf("0 %d %d",r[0],r[k-1]);
}
else
{
printf("%d %d %d",max[0].sum,max[0].first,max[0].last);
}
return 0;
}