The code didn’t pass a single test case but on giving custom input it gave correct output
#include<bits/stdc++.h>
using namespace std;
int main() {
int k;
char x[1000000];
cin>>k;
int a=0,b=0,sizea=0,sizeb=0;
cin>>x;
int l=strlen(x);
sizeb=sizea=l;
for(int i=0;x[i]!=’\0’;i++)
{
if(x[i]==‘a’ && b<=k)
{
b++;
sizeb=i+1;
}
}
for(int i=0;x[i]!=’\0’;i++)
{
if(x[i]==‘b’ && a<=k)
{
a++;
sizea=i+1;
}
}
int m=max(sizea,sizeb);
cout<<m;
return 0;
}
Code giving incorrect output
Hey @jha.aparna17,
You’re just considering the substring which starts with 0th index,
consider a case where the string is “ababababbbbbbbbbb” and k=3
The answer as per your logic, in this case, is 8 ababababbbbbbbbbb(changing all the ‘a’ to ‘b’ written in bold) , however, the correct answer is 16 ababababbbbbbbbbb (changing the first 3 ‘a’ to ‘b’).
You need to modify the code such that, the starting position of your answer substring can be variable too.
HINT: Think in terms of two pointers.