What is wrong with my code here

Q) Sanket Strings

@code_breaker-1001 Dry run your code for this test case-
2
abaabb
Your code output is 4
But it must be 5.
I am attaching my code below. Take it as a reference and then solve it again by your own.
`
import java.util.Scanner;

public class Main {

static int countMaxWindowSize(String s, char ch, int k) {
    int i = 0; 
    int j = 0; 
    int c = 0; 

    int ans = 0; 

    for (; c < k && j < s.length() - 1; j++) {
        if (s.charAt(j) != ch) {
            c++;
        }
        if (c == k) {
            break;
        }
    }

    while (i < j) {
        while (j < s.length() - 1 && s.charAt(j + 1) == ch) {
            j++;
        }
        int currentLength = j - i + 1;
        ans = Math.max(ans, currentLength);
        i++;
        if (j < s.length() - 1 && s.charAt(i - 1) != ch) {
            j++;
        }
    }

    return ans;
}

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int k = sc.nextInt();
    String s = sc.next();

    if (k >= s.length()) {
        System.out.println(s.length());
        return;
    }
    int ansForA = countMaxWindowSize(s, 'a', k);

    int ansForB = countMaxWindowSize(s, 'b', k);
    System.out.println(Math.max(ansForA, ansForB));
}

}

1 Like

Thanks. But just tell me why we need if condition for k >= str.length here in main string. Code is fine without it and I dont get any point in adding that…

Also I have 1 more dbt why does scanner take string input when using next but gives error with next line when used with int before…

@code_breaker-1001 Bro if k>=str.length then the straight away answer would be length of the string so there is not need to run the whole code just print the length.

@code_breaker-1001 Bro next takes the input of the string from new line but nextLine takes the input from the same line and jumps the cursor to new line after taking the input. Just read the difference and try it on demo code by yourself.

Ohk Thank you…

@code_breaker-1001 :+1: