1//I will encourage to first understand the problem then implement it on your know and do not just copy paste this code :) Regards
2#include <bits/stdc++.h>
3
4using namespace std;
5
6int main()
7{
8 string str;
9 cout<<"Enter the string :"<<endl;
10 cin>>str;
11 int k;
12 cout<<"Enter the number of unique characters required:"<<endl;
13 cin>>k;
14 map<char,int>mp;
15 int j=0;
16 int i=0;
17 int mx=INT_MIN;
18 int l=str.size();
19 while(j<l)
20 {
21 mp[str[j]]++;
22 if(int(mp.size())<k)
23 {
24 j++;
25 }
26 else if(int(mp.size())==k)
27 {
28 mx=max(mx,j-i+1);
29 j++;
30 }
31 else
32 {
33 while(int(mp.size())>k)
34 {
35 mp[str[i]]--;
36 if(mp[str[i]]==0)
37 {
38 mp.erase(str[i]);
39 }
40 i++;
41 }
42 j++;
43 }
44 }
45 cout<<mx<<endl;
46
47 return 0;
48}
49