Sanket and Strings Problem: What is wrong in my approach? It's giving wrong answers

import java.util.Scanner;
class Main{
public static Scanner scn = new Scanner(System.in);
public static void main(String[] args){
sanketStrings();
}

public static void sanketStrings(){
    int k = scn.nextInt();
    String str = scn.next();
    int count_a = 0;
    int count_b = 0;

    for(int i = 0;i< str.length();i++){
        if(str.charAt(i)=='a'){
            count_a++;
        }else{
            count_b++;
        }
    }
    int perfect = 0;
    if(count_a>count_b){
        perfect=count_a;
        if(count_b<=k){
            perfect = perfect + count_b;
        }else{
            perfect = perfect + k;
        }
    }else{
        perfect = count_b;
        if(count_a<=k){
            perfect = perfect + count_a;
        }else{
            perfect = perfect + k;
        }
    }

    System.out.println(perfect);

}

}

1
ababababaaba
its correct output is:4
And Your Code’s output is: 8

logic is not correct.
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’.


you can see this

Oh ,I got the problem with my logic

Question is asking for max length substring…Sorry :frowning:

Hey, can you once again share your code? It’s code replaced by a tree code now