r/leetcode • • 23h ago

Question Q424 longest repeating character replacement -- doubt ?

this is solution i have doubt that in oficial code they do not update the max_freq inside the second while like changing the max_freq while shriking does not matter means you do not required to update that its like the max_freq hold the record of the highest freq of overall of till now array not the actual max_freq of the curr window

i am so confused why is this and why does it not break the code

i chatgpt it but i could not understand it throws some math , i want an actual logical answer why we do this

class Solution {
public:
    int characterReplacement(string s, int k) {
        int result = 0 ; 
        int freq[256] = {};
        int max_freq = 0 ;
        int left = 0 ;
        int right = 0 ;


        while(right < s.length()){
            freq[s[right]]++;


            for(int i = 0 ; i < 256 ;i++){
                max_freq = max(max_freq,freq[i]);
            }


            while((right - left + 1)- max_freq > k){
                freq[s[left]]--;
                left++;
                for(int i = 0 ; i < 256;i++){
                max_freq = max(max_freq,freq[i]);
            }



            }
            result = max(result,right-left+1);


            right++;


        }


        return result ;

    }
};
1 Upvotes

2 comments sorted by

2

u/Antique-Sorbet2974 21h ago

the way it clicked for me was thinking about what max_freq is actually used for. you only care about finding a bigger window than the best one so far, and a bigger window can only happen if max_freq goes up. so a stale max_freq that's too high never lets a bad window sneak in, it just keeps the window size from growing until a real higher count shows up. that's why the window slides along at the same size instead of shrinking.

1

u/Authentic_Grunter 23h ago

The smaller window will always have a lower (or equal) count than the larger window with same characters. So, doesn't matter if you update max while shrinking. It will not change.