Header Ad

HackerEarth Hackers with Bits problem solution

In this HackerEarth Hackers with Bits problem solution Hackers love bits, so does Alex. Alex has just started his career as a hacker and found a special binary array A (containing 0s and 1s).

In one operation, he can choose any two positions in the array and can swap their values. He has to perform exactly one operation and maximize the length of the subarray containing only 1s.


HackerEarth Hackers with Bits problem solution


HackerEarth Hackers with Bits problem solution.

#include <cstdio>
#include <algorithm>

int a[123];

int n;

int count() {
int ones = 0;
int ret = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 1) {
++ones;
} else ones = 0;
ret = std::max(ret, ones);
}
return ret;
}

int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", a + i);
int ans = count();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
std::swap(a[i], a[j]);
ans = std::max(ans, count());
std::swap(a[i], a[j]);
}
}
printf("%d\n", ans);
}


Post a Comment

0 Comments