fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. string g;
  7. int n, k;
  8. cin >> n >> k >> g;
  9.  
  10. int maxi = -1;
  11.  
  12. for (int i = 0; i <= n - 1; i++)
  13. {
  14. unordered_map<char, int> b; // In this map only distinct characters and distinct frequency is stored
  15.  
  16. for (int j = i; j <= n - 1; j++)
  17. {
  18. // Count the current character
  19. char number = g[j]; // g[j] means original input string store in number
  20. b[number] = b[number] + 1; // and increment it count the currrent character
  21.  
  22. int l = j - i + 1;
  23.  
  24. // Check exactly k distinct characters
  25. if (b.size() == k) // b.size will give us number key- value pairs stored in map
  26. {
  27. maxi = max(maxi, l);
  28. }
  29. }
  30. }
  31.  
  32. cout << maxi << endl;
  33.  
  34. return 0;
  35. }
Success #stdin #stdout 0s 5320KB
stdin
7
2
aabaaab
stdout
7