链接:
https://codeforces.com/problemset/problem/1343/C
题意
给你m个长度为n的数组,里面由正数负数组成,要求你构建一个子数组由正负相间组成,例如[+, -, +, -],或者[-, +, -, +],并使其子数组和最大。
n <= 2e5
Example
input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
output
2
-1
6
-2999999997
解析
在循环数组的时候,使用双指针,寻找出连续同号的数中值最大的数,使得正的值越大,负的值越小,从而找到最大和的子数组。
#include <iostream>
using namespace std;
const int N = 2e5 + 10;
int q[N];
typedef long long ll;
int main()
{
int _;
cin >> _;
while (_--)
{
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> q[i];
ll ans = 0;
for (int i = 0, j; i < n; i++)
{
int t = q[i];
j = i;
while ((q[j] > 0 && q[j + 1] > 0 || q[j] < 0 && q[j + 1] < 0) && j < n - 1)//这里修改过很多遍,如果判断条件换成q[j] * q[j + 1] > 0就会判题wrong answer,暂时不知道原因,改成代码里的判断条件就没问题
{
if (t < q[j + 1]) t = q[j + 1];
j++;
}
ans += t;
i = j;
}
cout << ans << endl;
}
return 0;
}