FREQ2 - Most Frequent Value - SPOJ Solution C++

  Problem Link : FREQ2 


👉 Hint : edit please

 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

int blk_size;

struct query
{
	int lt,rt,ind;
};

bool comp(query x,query y)
{
	if(x.lt/blk_size != y.lt/blk_size)
		return x.lt/blk_size < y.lt/blk_size;

	return x.rt < y.rt;
}


int main()
{

	int n,q,l,r,mol,mor;
	scanf("%d %d",&n,&q);
	blk_size=sqrt(n);
	int arr[n],cnt[100001]={0},freq[100001]={0};
	query qarr[q];
	for(int i=0;i<n;i++)
	{
		scanf("%d",&arr[i]);
	}
	int ans[q];
	
	for(int i=0;i<q;i++)
	{
		scanf("%d %d",&l,&r);
		qarr[i].lt=l;
		qarr[i].rt=r;
		qarr[i].ind=i;
	}
	sort(qarr,qarr+q,comp);

	mol=0;
	mor=-1;
	int curr_l;
	int curr_r;
	int qans=0;
	int mf=-1;
	for(int i=0;i<q;i++)
	{
		curr_l=qarr[i].lt;
		curr_r=qarr[i].rt;
		while(mor<curr_r)
		{
			mor++;
			freq[cnt[arr[mor]]]--;
			cnt[arr[mor]]++;
			freq[cnt[arr[mor]]]++;	
			if(cnt[arr[mor]]>qans)
				qans=cnt[arr[mor]];
		}
		while(mor>curr_r)
		{
			
			if(cnt[arr[mor]]==qans)
			{
				if(freq[cnt[arr[mor]]]==1)
					qans=cnt[arr[mor]]-1;
			}
			freq[cnt[arr[mor]]]--;
			cnt[arr[mor]]--;
			freq[cnt[arr[mor]]]++;
			mor--;

		}
		while(mol>curr_l)
		{
			mol--;
			freq[cnt[arr[mol]]]--;
			cnt[arr[mol]]++;
			freq[cnt[arr[mol]]]++;	
			if(cnt[arr[mol]]>qans)
				qans=cnt[arr[mol]];
		}
		while(mol<curr_l)
		{
			
			if(cnt[arr[mol]]==qans)
			{
				if(freq[cnt[arr[mol]]]==1)
					qans=cnt[arr[mol]]-1;
			}
			freq[cnt[arr[mol]]]--;
			cnt[arr[mol]]--;
			freq[cnt[arr[mol]]]++;
			mol++;
		}

		ans[qarr[i].ind]=qans;

	}
	for(int i=0;i<q;i++)
		printf("%d\n",ans[i]);

}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!