fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8.  
  9. int n = sc.nextInt();
  10. int k = sc.nextInt();
  11. sc.nextLine();
  12.  
  13. String s = sc.nextLine();
  14.  
  15. TreeMap<Character, Integer> map = new TreeMap<>();
  16.  
  17. int left = 0;
  18. int maxLength = 0;
  19.  
  20. for (int right = 0; right < n; right++) {
  21.  
  22. char ch = s.charAt(right);
  23.  
  24. // Add current character
  25. map.put(ch, map.getOrDefault(ch, 0) + 1);
  26.  
  27. // Shrink window while invalid
  28. while (map.lastKey() - map.firstKey() > k) {
  29.  
  30. char leftChar = s.charAt(left);
  31.  
  32. map.put(leftChar, map.get(leftChar) - 1);
  33.  
  34. if (map.get(leftChar) == 0) {
  35. map.remove(leftChar);
  36. }
  37.  
  38. left++;
  39. }
  40.  
  41. maxLength = Math.max(maxLength, right - left + 1);
  42. }
  43.  
  44. System.out.println(maxLength);
  45. }
  46. }
Success #stdin #stdout 0.11s 54544KB
stdin
8 2
abdcbbca
stdout
6