why -1 is coming as answer. plzz rectify my code
Wrong answer coming
@nagpalyash4 Your code is not working bcoz in sliding_find function your while loop condition is such that the while loop is not executing even once. bcoz your n is 0 for all iterations in charReplacement function and your arr is coming out to be zero size bcoz when you have taken input in main function
int k = sc.nextInt();//Takes n input
but now when you take String str = sc.nextLine(); //this will take input after int k which is empty bcoz your string is nin next line but sc.nextLine() takes input of current line and moves the cursor to next and since your cursor was on the line of int k that’s why you’re getting empty. To solve this bug use sc.next() instead of sc.nextLine();
ii)Since all the characters in the input string will be lowercase so in charReplacement function loop use smaller ‘a’ and small ‘z’.
iii)Your logic has some deficiencies so use below approach for correct answer :
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’.
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.