fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7.  
  8. int n = sc.nextInt(); // Read n
  9. int k = sc.nextInt(); // Read k
  10. sc.nextLine(); // Consume newline after integers
  11. String s = sc.nextLine(); // Read the input string
  12.  
  13. int[] dp = new int[n];
  14. dp[0] = 1; // The first character is always a valid substring of length 1
  15.  
  16. int maxLen = 1; // The maximum length of valid substring
  17. int maxIndex = 0; // The index where the maximum valid substring ends
  18.  
  19. // Fill the dp array
  20. for (int i = 1; i < n; i++) {
  21. if (Math.abs(s.charAt(i) - s.charAt(i - 1)) <= k) {
  22. dp[i] = dp[i - 1] + 1; // Extend the valid substring
  23. } else {
  24. dp[i] = 1; // Start a new valid substring
  25. }
  26.  
  27. // Update maxLen and maxIndex if a longer valid substring is found
  28. if (dp[i] > maxLen) {
  29. maxLen = dp[i];
  30. maxIndex = i;
  31. }
  32. }
  33.  
  34. // Get the start index of the largest valid substring
  35. int startIndex = maxIndex - maxLen + 1;
  36.  
  37. // Print the largest valid substring
  38. System.out.println(s.substring(startIndex, startIndex + maxLen));
  39.  
  40. sc.close();
  41. }
  42. }
  43.  
Success #stdin #stdout 0.11s 56540KB
stdin
6 1 
zebraa
stdout
aa