Problem:
We have an array of N elements(size upto 10^5) and We need to have q queries(upto 10^5) , of type:
!-> right rotate the array
?-> print maximum consecutive ones in the array <=k(k is an upperbound, if we find maximum consecutive ones >k print k)
Array elements are only of type 0's and 1's,
My code times out (time limit 1sec) for the constraints mentioned, lease tell me some better approach or optimization for this code :
Example input:
5 5 3
1 1 0 1 1
?!?!?
Example output:
2
3
3
Code:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef vector<int> vi
vi rrot(vi vec, int k, int n)
{
k %= n;
k = n-k;
rotate(vec.begin(), vec.begin()+k,vec.end());
return vec;
}
int findone(vi nums,int k) {
vi result;
vi zero_index;
for (int i=0;i<nums.size();i++)
{
if (nums[i]==0)
zero_index.push_back(i);
}
zero_index.insert(zero_index.begin(),-1);
zero_index.push_back(nums.size());
for(int i=0;i<zero_index.size()-1;i++)
{
result.push_back(zero_index[i+1]-zero_index[i]-1);
}
int val= *max_element(result.begin(),result.end());
if(val<k) return val;
return k;
}
int main() {
LL n,q,k;cin>>n>>q>>k; //n is length of sequence of 1s and 0s , q is number of queries k is upperbound to max ones
vi arr(n);
for(int i=0;i<n;i++) {cin>>arr[i];}
vi queries;
string quer;cin>>quer; //input quer string
int c=0;
//ALGO: Basically stored consecutive '!' to get a number of jumps neede to make before '?' query, this one rather doing one by one rotations I can simply rotate to 'c' jumps
for(int i=0;i<quer.length();)
{
while(quer[i]=='!')
{
c++;i++;
}
queries.push_back(c);
i++;
}
for(int i=0;i<queries.size();i++)
{
vector<int> temp=arr; //get original array and store in temporary
temp=rrot(temp,queries[i],n);
cout<<findone(temp,k)<<"\n"; //print result...
}
return 0;
}