![]() |
VOOZH | about |
Given a string s of length n consisting only of uppercase English letters ('A'–'Z') and an integer k (0 ≤ k ≤ n), you can change at most k characters in the string. Find the length of the longest substring that can be made of all same character after performing at most k changes.
Input : k = 2, s = ABABA
Output : 5
We can get maximum length by replacing 2 B's with A'sInput : k = 4, s = HHHHHH
Output : 6
We get maximum length 6 without any replacement
Table of Content
- Consider all substrings by choosing start l and end r.
- For each substring, find the most frequent character..
- If (substring length − max frequency) ≤ k, update the maximum length.
Dry run for k = 1, s = "ABA"
For every substring, we compute the most frequent character and check if remaining characters (to be replaced) are within k; the maximum valid length obtained is 3.
5 6
- Check each character from 'A' to 'Z' and treat it as the target character for the substring.
- Use a sliding window to find the longest substring that can be converted to that character with at most k changes.
- If the number of different characters exceeds k, shrink the window from the left.
- Track the maximum substring length among all characters and return it.
5 6
- Maintain a sliding window (l, r) and store character frequencies using a hash map.
- Track the most frequent character (maxFreq) in the window.
- If (window size − maxFreq) > k, shrink the window; otherwise expand it and update the maximum length.
Dry run for k = 2, s = "ABABA"
Final answer is 5.
5 6