Intuition
For every possible substring, count the most frequent character and check if the remaining characters can be replaced within k operations.
Explanation
Brute Force
Enumerate every substring (i, j). For each one, count character frequencies, find the most frequent character count maxFreq, and check if (j - i + 1) - maxFreq <= k. If so, the substring can become all one character with at most k replacements. Track the longest valid one.
This requires O(n^2) substrings and O(26) work per substring to count frequencies, giving O(26 * n^2) = O(n^2) time. Space is O(26) = O(1) for the frequency counter.
Why it's slow: we re-examine overlapping substrings instead of incrementally adjusting a window.
Implementation
class Solution {
public int characterReplacement(String s, int k) {
int n = s.length();
int best = 0;
for (int i = 0; i < n; i++) {
int[] count = new int[26];
int maxFreq = 0;
for (int j = i; j < n; j++) {
count[s.charAt(j) - 'A']++;
maxFreq = Math.max(maxFreq, count[s.charAt(j) - 'A']);
if ((j - i + 1) - maxFreq <= k) {
best = Math.max(best, j - i + 1);
}
}
}
return best;
}
}