题目链接:点击打开链接
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;
}