AceYourInterviews
Checking sign-in…

22. Longest Repeating Character Replacement

IntermediateHistorical-frequency maximum-length window

Choose a contiguous substring and replace at most k of its characters so that every position in that substring contains the same uppercase letter. Return the largest possible length.

The budget counts changed positions, not distinct letters. You may choose which final letter to use and may perform fewer than k replacements.

Example 1

Input

s="AABABBA", k=1

Output

4

Explanation: AABA can become AAAA by changing its B. Later retained windows of length four need not themselves be feasible.

Example 2

Input

s="ABCDE", k=0

Output

1

Explanation: No changes are available, so only an already-uniform run qualifies.

Constraints

  • 0 <= s.length <= 105
  • 0 <= k <= 231 - 1
  • s contains only uppercase English letters A–Z.
Hints
Hint 1

For one window, how many positions differ from its dominant character?

Hint 2

What does a historical maximum allow you to reject safely?

Hint 3

Keep the historical count for length only, and explain why each new record length has an earlier feasible witness.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Historical and true maxima diverge

"AABABBA"
1
4