Sanket and strings

public static void main(String[] args) {
Scanner scn=new Scanner(System.in);

	int n=scn.nextInt();
	String str1= scn.next();

	StringBuilder str=new StringBuilder(str1);
	int counta=0, countb=0;
	for (int i=0;i<str.length();i++) {
		if (str.charAt(i)=='a'){
			counta++;
		}
		else {
			countb++;
		}
	}
	int count =0;
	if (counta>countb) {
		for (int i=0;i<str.length() && count<=n;i++ ) {
			if (str.charAt(i)=='b') {
				str.setCharAt(i,'a');
				count++;
				counta++;
			}
		}
	}
	else {
		for (int i=0;i<str.length() && count<=n;i++ ) {
			if (str.charAt(i)=='a') {
				str.setCharAt(i,'b');
				count++;
				countb++;
			}
		
	   }
	}
	
	System.out.println(counta);
}

what is wrong in this code??

Hey @harsh.hj
You are doing wrong
Try for this input
2
abba
correct ans : 4

but my ans is coming 2

yes
but correct output is 4

so my doubt is how to modify this code???

@harsh.hj
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’.
    If you are not able to write a code, I will send it to you. But try yourself first