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

本文介绍了一个算法,用于解决给定整数数组中连续子数组和的最大值问题。通过遍历数组并跟踪当前子数组和,该算法能够找到最大的连续子数组和。示例代码提供了一个实现解决方案的方法,包括输入输出格式和处理流程。

3131

被折叠的 条评论
为什么被折叠?



