fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String s1 = "bca";
  13. int k1 = 1;
  14. System.out.println("Test Case 1 Max Length: " + longestValidSubstring(s1, k1));
  15. }
  16.  
  17. public static int longestValidSubstring(String s, int k) {
  18. int n = s.length();
  19. if (n == 0) return 0;
  20.  
  21. // dp[i] stores the length of the longest valid substring ending at index i
  22. int[] dp = new int[n];
  23.  
  24. // Base case: a single character is always a valid substring of length 1
  25. dp[0] = 1;
  26. int maxLength = 1;
  27.  
  28.  
  29. for (int i = 1; i < n; i++) {
  30. if (Math.abs(s.charAt(i) - s.charAt(i - 1)) <= k) {
  31. dp[i] = dp[i - 1] + 1;
  32. } else {
  33. dp[i] = 1;
  34. }
  35.  
  36. maxLength = Math.max(maxLength, dp[i]);
  37. }
  38.  
  39. return maxLength;
  40. }
  41. }
Success #stdin #stdout 0.12s 55588KB
stdin
Standard input is empty
stdout
Test Case 1 Max Length: 2