616D. Longest k - Codeforces Solution C++

  Problem Link : 616D. Longest k 


✅ C++ Solution :

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

#define ll long long int

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	ll n,k;
	cin>>n>>k;
	ll arr[n+1];
	for(int i=1;i<=n;i++)
		cin>>arr[i];

	int i=1;
	int ai=-1,aj=-2;
	int mp[1000001]={0};
	int cnt=0;
	for(int j=1;j<=n;j++)
	{
		mp[arr[j]]++;
		if(mp[arr[j]] == 1)
			cnt++;
		while(i<j && cnt>k)
		{
			mp[arr[i]]--;
			if(mp[arr[i]]==0)
				cnt--;
			i++;
		}

		if(aj-ai < j-i)
			aj=j,ai=i;
	}
	cout<<ai<<" "<<aj;
}

 

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!!