Example 1
- Input
- s = "ABAB", k = 2
- Output
- 4
Replace the two A letters with B letters (or vice versa) to get "BBBB", a run of length 4.
Given a string of uppercase letters and an integer k, you may change at most k characters to any other uppercase letter. Return the length of the longest substring that can be turned into a run of one repeated letter.
Given a non-empty string s of uppercase English letters and an integer k, you may replace at most k characters with other uppercase English letters. Return the maximum length of a contiguous substring that can contain just one repeated letter after those changes. Return a length, not the changed string, and do not actually modify s.
For a candidate window of length L with most frequent letter count F, keeping that letter and replacing all others costs exactly L - F changes. The window is genuinely feasible when L - F <= k.
1 <= s.length <= 10^5s consists of only uppercase English letters.0 <= k <= s.lengthReplace the two A letters with B letters (or vice versa) to get "BBBB", a run of length 4.
Replace the middle A with B to get "AABBBBA", which contains the run "BBBB" of length 4.
No replacements are allowed, and adjacent letters differ, so only a single-letter substring is uniform.
The full string is already one repeated letter and costs zero replacements.
Keeping any one letter requires replacing four positions, within the allowed budget. The answer cannot exceed the original length.
Keep the letter already occurring most often in a candidate substring, since every other letter costs one replacement. In ABAB, A and B each occur twice: keeping either one changes two of the four positions, so k = 2 allows the full length 4. Extending a window may create a better answer; removing from its left lets the search continue without restarting. The optimized algorithm remembers a historical frequency bound to search for a length, so its current window need not always be genuinely feasible.
Reveal Brute Force: intuition, complexity, and code
A budgeted window can use a historical frequency bound when the requested output is a maximum length and record growth has a feasible witness. Distinguish this optimization from maintaining an exactly valid current substring.