fork download
  1. // same two pointer original template optimal logic is use
  2. // just change with respect to question
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. int n, k;
  10. string s;
  11. cin >> n >> k >> s;
  12.  
  13. // Store each character and its frequency in the window
  14. unordered_map<char, int> b;
  15.  
  16. int i = 0; // Left pointer of the window
  17. int maxi = -1; // Longest valid substring length
  18.  
  19. // j is the right pointer of the window
  20. for (int j = 0; j < n; j++)
  21. {
  22. // Add the current character to the window
  23. b[s[j]] = b[s[j]] + 1;
  24.  
  25. // If distinct characters exceed k, i mean greater than k
  26. // shrink the window from the left
  27. while (b.size() > k) // in two pointer template sum > k same here we put with respect to question
  28. {
  29. b[s[i]] = b[s[i]] - 1; // remove that element // same two pointer template sum = sum - b[i]
  30.  
  31. // Remove the character from the map
  32. // if its frequency becomes zero
  33. if (b[s[i]] == 0)
  34. {
  35. b.erase(s[i]);
  36. }
  37.  
  38. // Move the left pointer forward
  39. i++;
  40. }
  41.  
  42. // Check if the window has exactly k distinct characters then it will come directly but if the window is greater than only it will go in while loop
  43. if (b.size() == k)
  44. {
  45. // here calculating the maximum window length
  46. maxi = max(maxi, j - i + 1);
  47. }
  48. }
  49.  
  50. // Print the longest valid substring length
  51. cout << maxi << endl;
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 5320KB
stdin
7
2
aabaaab
stdout
7