Need Some Hint how to approach this problem

Cant make the logic and how to start this problem.

You can solve this problem in O(n) time using the two pointer approach.

  • Make two variabes , say i and j .
  • i defines the beginning of a window and j defines its end.
  • Start i from 0 and j from k.
  • Let’s talk about the singular case when we are considering the max window for only 'a’s and consider only the swapping of b-> a. If we are able to get the answer for max window of consecutive 'a’s , we can simply implement the same algo for the max ‘b’ window as well.
  • So we started i from 0 and j from k.
  • Move j ahead freely as long as there are ‘a’ characters at s[ j ] position.
  • Maintain a count variable which counts the number of swaps made or the number of 'b’s in our A window.
  • If you encounter a ‘b’ char at s[ j ] position , increment the count variable. Count should never exceed k .
  • Take the size of the window at every point using length = j - i + 1;
  • Compute the max size window this way and do the same for ‘b’ as well.
  • Output the maximum size window of ‘a’ and ‘b’.

refer this code --> https://ide.codingblocks.com/s/642677

hi @mohit26900
i hope its clear now… is there anything else??

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

@mohit26900 we can easily solve this problem using 2 pointer sliding window approach
refer to below code for more clarity

#include <bits/stdc++.h>
using namespace std;

int main() {
int k;
cin>>k;
string s;
cin>>s;

int n=s.length();
int l=0,r=0;
int ans=0;
int counta=0,countb=0;
while(l<=r && l<n && r<n)
{
	if(counta>k || countb>k)
	{
		while(counta>k || countb>k)
		{
			if(s[l]=='a')
			counta--;
			if(s[l]=='b')
			countb--;
			l++;
		}
	}
	else
	{
		ans=max(ans,r-l+1);
		if(s[r]=='a')
		counta++;
		else
		countb++;
		
		r++;
	}
}
cout<<ans<<endl;
return 0;

}

Ip: string = “abba” k=2
op: 4

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.