@toc
问题描述
给你一个由 n 个整数 a1,a2,…,an 组成的数组
。整数为 1 或 −1。您必须在数组 a 上恰好执行一次以下操作:
选择一个索引 i (1≤i<n) 并翻转 ai 和 ai+1 的符号。在这里,翻转符号意味着 −1 将是 1,1 将是 −1。
应用上述操作后 a1+a2+…+an 的最大可能值是多少?
格式输入
每个测试包含多个测试用例。第一行包含测试用例 t (1≤t≤500) 的数量。测试用例的说明如下。
每个测试用例的第一行包含一个整数 n (2≤n≤105),数组 a 的长度。
下一行包含 n 个整数 a1,a2,…,an (ai=1 或 ai=−1)。
所有事例的 n 之和不超过 105。
格式输出
对于每个测试用例,在单独的行中打印数组的最大可能总和。
样例输入
4
5
-1 1 1 -1 -1
5
1 1 -1 -1 -1
2
1 1
4
1 -1 -1 1
样例输出
3
3
-2
4
评测用例规模与约定
每次测试的时间限制1 秒
每个测试的内存限制256 MB
参考程序
#include<iostream>
using namespace std;
const int N = 100010;
int a[N];
int m;
int main()
{
cin >> m;
while (m--)
{
int cnt, hhh;
cnt = 0, hhh = 0;
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n; i++)
{
if (a[i] == -1) cnt++;
if (a[i] == -1 && a[i + 1] == -1) hhh = 1;
}
int sub = 0;
for (int i = 0; i < n; i++) sub += a[i];
if (cnt == 0) { int h = sub - 4; cout << h; }
if (cnt == 1) cout << sub;
if (cnt >= 2 && hhh == 1) { int j = sub + 4; cout << j; }
else { if (cnt >= 2) cout << sub; }
cout << endl;
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000;
int main(){
int t;
cin >> t;
for (int i = 0; i < t; i++){
int n;
cin >> n;
vector<int> a(n);
for (int j = 0; j < n; j++){
cin >> a[j];
}
int s = 0;
for (int j = 0; j < n; j++){
s += a[j];
}
int ans = -INF;
for (int j = 0; j < n - 1; j++){
ans = max(ans, s - a[j] * 2 - a[j + 1] * 2);
}
cout << ans << endl;
}
}
以个人刷题整理为目的,如若侵权,请联系删除~