Problem in sanketAndStrings

Can anyone please tell me what corner case i m missing in SanketAndStrings problem…
my code :


i m getting wrong answer for two test cases…

Hello @gauravrai628,

The following code will execute only until k>0.
And you are not incrementing it’s value anywhere in code again.
It will fail for a case , where first k swaps would not provide the optmial solution:
example:
3
abbaabaabaaaaaaaaa

	for( r=l+1;k>0,r<sz(s);r++){
		if(s[r]!=s[l])
			k--;
		length++;
	}

Can you explain the logic for the following code:
if(k==0)
while(s[r]==s[l]){
length++;r++;
}
maxlength=max(length,maxlength);
}

As once k goes 0, it will always execute.
This is causing the wrong output for above mentioned testcase: 18
Expected output is 16.

You can take help of the following approach, it is a general way:
Perform following for both the characters a and b individually,

  1. Take two pointer l and r to mark the left and right index of the string under consideration.
  2. starting from l=0,r=0,max=0,count=0.
  3. repeat untill r <n (n is length of string)
    3.1. increase the count whenever you find a different character(by different we mean if we are forming a string of a only, then b is different).
    3.2. while count is greater than k,
    …3.2.1. decrement the count by one if element at lth index is different.
    …3.2.1. increment l.
    3.3. Compare max with count for maximum value.
    3.4. increment r.

If you still have issues or you don’t understand anything, feel free to ask.
Hope, this would help.
Give a like, if you are satisfied.

1 Like

got that !!!.
thanks :+1:

Mark your doubt as resolved if you have no more left regarding this question.