Header Ad

HackerEarth Average Subarray problem solution

In this HackerEarth Average Subarray problem solution, You are given an binary array A of N integers. You are also given an integer K and you need to ensure that no subarray of size greater than or equal to K has average 1.
For this you can perform the below operation:

Choose any index and flip the bit.
Find the minimum number of operations to acheive the above condition.


HackerEarth Average Subarray problem solution


HackerEarth Average Subarray problem solution.

#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mod 1000000007
#define endl "\n"
#define test ll t; cin>>t; while(t--)
typedef long long int ll;
int main() {
FIO;
test
{
ll n,q; cin>>n>>q;
vector<ll>x(n),r(n);
for(auto &it:x) cin>>it;
for(auto &it:r) cin>>it;
vector<ll>ans(4*n+5,0);
for(int i=0;i<n;i++){
int left=x[i]-r[i]+2*n;
int right=x[i]+r[i]+2*n+1;
if(x[i]>0){
left=max(left,2*n);
}
else{
right=max(right,2*n);
}
ans[left]++;
ans[right]--;
}
for(int i=1;i<4*n+5;i++){
ans[i]+=ans[i-1];
}
while(q--){
int inp; cin>>inp;
inp+=2*n;
cout<<ans[inp]<<endl;
}
}
return 0;
}

Second solution

t = int(input())

while t > 0:
t -= 1
n, k = map(int, input().split())
cnt = ans = 0
for x in input().split():
if x == '1':
cnt += 1
if cnt == k:
ans += 1
cnt = 0
else:
cnt = 0
print(ans)


Post a Comment

0 Comments