Optimal: window with a max-count
Time O(n) Space O(26)Count letters in the window and track maxCount, the highest count seen. If length − maxCount > k, move left by one (the window slides without growing). maxCount can stay stale: a longer answer requires a larger max count, so a stale value never causes a wrong larger answer.
class Solution {
public int characterReplacement(String s, int k) {
int[] count = new int[26];
int left = 0, maxCount = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
maxCount = Math.max(maxCount, ++count[s.charAt(right) - 'A']);
if (right - left + 1 - maxCount > k) {
count[s.charAt(left) - 'A']--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
}Verdict: Linear with a 26-letter count array.