codeforce848.A题

@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;
  }
}

以个人刷题整理为目的,如若侵权,请联系删除~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值