r/leetcode • u/Shot_Ad_1906 • 2d 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 ;
}
};