HDOJ1003 Max Sum(脑洞)

题目链接:点击打开链接


t组样例,每组样例开始是n,后n个数字组成一个数组。问你连续的哪些数之和最大。


每读入一个数字加到tmp上,代表当前数之和,若tmp比ans大则更新ans,同时更新起始和结束的点。若tmp为负则更新起点为j+1,

且tmp重置为0。保证了ans能取得最大。


AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1e5 + 5;
const int INF = 0x3f3f3f3f;
int n, a[MAXN];
int main(int argc, char const *argv[])
{
	int t;
	scanf("%d", &t);
	for(int cas = 1; cas <= t; ++cas) {
		scanf("%d", &n);
		int ans = -INF, tmp = 0, x, st, ed;
		for(int i = 1, j = 1; j <= n; ++j) {
			scanf("%d", &x);
			tmp += x;
			if(tmp > ans) {
				ans = tmp;
				st = i;
				ed = j;
			}
			if(tmp < 0) {
				i = j + 1;
				tmp = 0;
			}
		}
		printf("Case %d:\n", cas);
		printf("%d %d %d\n", ans, st, ed);
		if(cas != t) printf("\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值