size − max_count ≤ k.Inside any window, the most-common letter appears max_count times. Every other letter is something we'd have to swap to make the whole window the same letter.
So window_size − max_count = the number of "wrong" letters we'd need to replace. If that's ≤ k, the window is achievable within our swap budget. If not, shrink from the left.
The clever optimization: we never refresh max_count when the window shrinks. It can only go up across the whole run. A "stale" max_count just means the window stays open one or two extra steps — but the best we record is always achievable, because best ≤ max_count + k and max_count was set by a real window.
Net: each character is touched O(1) times by RIGHT (push) and O(1) times by LEFT (pop). Total O(n). The set-of-substrings brute force is O(n³).
Same shape carries over to: Longest Substring Without Repeating, Min Window Substring, Permutation in String.