1007. Maximum Subsequence Sum (25)

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;
}

       

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值