Given an array, we need to find the longest contiguous subarray that has the same element in range l to r for multiple queries. For example, ar[] = {1,2,2,2,4,3,1,1,3}.
Query 1: l=1,r=5, element=2, output will be 3
Query 2: l=1,r=5, element=1, output will be 1
Query 3: l=6,r=9, element=3, output will be 1
Query 4: l=6,r=9, element=1, output will be 2
I can run a loop from l to r and calculate the longest contiguous occurance of the given element in the range, but I need a better approach. Constraints are 1<=l,r,no. of queries, size of array<=100000 Here is my brute force code:
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll i,j,k,m,n,l,r,x;
n=9;
ll ar[n]={1,2,2,2,4,3,1,1,3};
ll query=4;//number of queries
while(query--)
{
cin>>l>>r>>x;
l--;r--;//changing to 0-based indexing
ll ctr=0;
ll ans=0;
for(i=l;i<=r;i++)
{
if(ar[i]==x)
{
ctr++;
}
else ctr=0;
ans=max(ctr,ans);
}
cout<<ans<<endl;
}
}