Untitled

 avatar
unknown
plain_text
23 days ago
1.3 kB
1
Indexable
public class Solution {
    public int characterReplacement(String s, int k) {
        int n = s.length();
        int[] arr = new int[26]; // To count frequencies of characters in the window
        int maxFreq = 0; // Maximum frequency of a single character in the current window
        int maxLength = 0;
        int i = 0; // Left pointer of the window
        int j = 0;
        while(j<n){ // Right pointer of the window
            // Update the frequency of the current character
            arr[s.charAt(j) - 'A']++;
            // Update the maximum frequency of any character in the window
            maxFreq = Math.max(maxFreq, charCount[s.charAt(j) - 'A']);

            // Check if the window is valid: 
            // Total characters minus the most frequent character count should be <= k
           // can be replaced with if
            if ((j - i + 1) - maxFreq > k) {
                // Shrink the window from the left
                arr[s.charAt(i) - 'A']--;
                i++;
            }

           
            // Update the maximum length of the valid window
          if((j - i + 1) - maxFreq <= k)
            maxLength = Math.max(maxLength, j - i + 1);
          j++;
        }

        return maxLength;
    }
}
Leave a Comment