Here is an optimization that looks like a mistake: the variable tracking the most frequent character in the window is wrong. It never decreases, even when it should. And the algorithm still produces the correct answer every time.
If that bothers you, good. It bothered me for three days before I traced through the invariant proof and stopped flinching. The problem: given a string and an integer k, find the longest substring where you can replace at most k characters to make every character in the substring the same.
The approach looks straightforward at first: expand, track characters, shrink when needed. But the devil is in how you track the most frequent character. Let us see why the obvious approach wastes enormous effort.
Consider the string "AABABBA" with k = 1. You can replace at most one character. The validity condition for any window is simple: windowLength - maxFreq <= k. If the most frequent character appears maxFreq times in the window, you need to replace windowLength - maxFreq other characters. If that fits within your budget k, the window is valid.
The sliding window expands right. After each expansion, you need to know the most frequent character in the window. The obvious approach: scan all character frequencies and pick the maximum. Let us try that and see what it costs.