Advertisement
rajeshinternshala

Untitled

Nov 17th, 2023
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.73 KB | None | 0 0
  1.  public static int maxLength(String X, String Y, int K) {
  2.         int n = X.length();
  3.         int cost = 0, len = 0, maxlen = 0;
  4.         for (int i = 0; i < n; i++) {
  5.             cost += Math.abs(X.charAt(i) - Y.charAt(i)); // calculate the cost of changing the characters at each index i within the window.
  6.             len++;
  7.             while (cost > K) { // if the total cost of changing the characters within the window is more than K, shrink the window from the left to decrease the cost.
  8.                 cost -= Math.abs(X.charAt(i - len + 1) - Y.charAt(i - len + 1));
  9.                 len--;
  10.             }
  11.             maxlen = Math.max(maxlen, len); // update the maximum length seen so far.
  12.         }
  13.         return maxlen;
  14.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement