描述
给定一整型数列{a1,a2...,an},找出连续非空子串{ax,ax+1,...,ay},使得该子序列的和最大,其中,1<=x<=y<=n。
输入第一行是一个整数N(N<=10)表示测试数据的组数) 每组测试数据的第一行是一个整数n表示序列中共有n个整数,随后的一行里有n个整数I(-100=<I<=100),表示数列中的所有元素。(0<n<=1000000)输出对于每组测试数据输出和最大的连续子串的和。样例输入
1
5
1 2 -1 3 -2
样例输出
5
#include <iostream>
#include <string>
#include <stack>
#include <set>
#include <memory.h>
#include <map>
#include <iomanip>
#include <queue>
#include <algorithm>
#define max(a,b) (a>b ? a:b)
using namespace std;
int dp[1000001];
int arr[1000001];
int main()
{
int n;
int t;
cin >> t;
while (t--)
{
cin >> n;
int flag = 0;
int M = -99999999;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
if (arr[i]>0)
flag = 1;
if (arr[i] > M)
M = arr[i];
}
if (flag == 0)
{
cout << M << endl;
continue;
}
memset(dp, 0, sizeof(dp));
dp[0] = arr[0];
int Max = -9999999;
for (int i = 1; i < n; i++)
{
if (dp[i - 1] >= 0)
dp[i] = dp[i - 1] + arr[i];
else
dp[i] = arr[i];
if (dp[i]>Max)
Max = dp[i];
}
cout << Max<< endl;
}
return 0;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有