You are given a binary array† of length n. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a 0 into a 1 or vice-versa.
What is the maximum number of inversions‡ the array can have after performing at most one operation?
† A binary array is an array that contains only zeroes and ones.
‡ The number of inversions in an array is the number of pairs of indices i,j such that iaj.
Input
The input consists of multiple test cases. The first line contains an integer t (1≤t≤104) — the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer n (1≤n≤2⋅105) — the length of the array.
The following line contains n space-separated positive integers a1, a2,…, an (0≤ai≤1) — the elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅105.
Output
For each test case, output a single integer — the maximum number of inversions the array can have after performing at most one operation.
Example
inputCopy
5
4
1 0 1 0
6
0 1 0 0 1 0
2
0 0
8
1 0 1 1 0 0 0 1
3
1 1 1
outputCopy
3
7
1
13
2
Note
For the first test case, the inversions are initially formed by the pairs of indices (1,2), (1,4), (3,4), being a total of 3, which already is the maximum possible.
For the second test case, the inversions are initially formed by the pairs of indices (2,3), (2,4), (2,6), (5,6), being a total of four. But, by flipping the first element, the array becomes 1,1,0,0,1,0, which has the inversions formed by the pairs of indices (1,3), (1,4), (1,6), (2,3), (2,4), (2,6), (5,6) which total to 7 inversions which is the maximum possible.
#include
using namespace std;
typedef long long ll;
int t, n;
int a[200005];
int fro[2][200005];//前缀
int back[2][200005];//后缀
int main() {
cin >> t;
while (t--) {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
//求前缀,求i前面1的个数和0的个数
int one = 0, zero = 0;
for (int i = 1; i <= n; ++i) {
fro[1][i] = one;
fro[0][i] = zero;
if (a[i])
one++;
else
zero++;
}
//求后缀,每个位置后面的1和0的个数
one = 0, zero = 0;
for (int i = n; i >= 1; --i) {
back[1][i] = one;
back[0][i] = zero;
if (a[i])
one++;
else
zero++;
}
ll ans = 0;
//不翻转时候
for (int i = 1; i <= n; ++i) {
if (a[i]) {
ans += back[0][i];
}
}
//逐个翻转判断
ll temp = ans;//不翻转的方案数
for (int i = 1; i <= n; ++i) {
//把1变为0,方案数temp 减1后面是0的个数,加1前面是1的个数
if (a[i]) {
ans = max(ans, (temp - back[0][i] + fro[1][i]));//这里是对temp操作的,在他基础上变化方案数
} else {
//0变为1,方案数 减0前面1的个数,加0后面0的个数
ans = max(ans, (temp - fro[1][i] + back[0][i]));
}
}
cout << ans << endl;
}
return 0;
}