SanketAndStrings

#include
using namespace std;

int main()
{
int k;
cin>>k;

string s;
cin>>s;

int a=0, b=0, maxa=-1, maxb=-1;

for(int j=0;j<s.length();j++)
{
     // find maximum substring length containing of 'a'

    if(s[j]=='a')
    {
        a++;
        b=0;

        maxa=max(a,maxa);
    }

    // find maximum substring length containing of 'b'

    else
    {
        b++;
        a=0;

         maxb=max(b,maxb);
    }  
}

int ans = max( maxa, maxb);  // maximum length of substring containing same chars either 'a' or 'b'


cout<<ans+k;      // add the k in ans

}

Why I am not getting the desired output on submission ?

Hi @vaishnavtannu
You are not getting desired output because this is not an optimal approach that you are using. Instead you should use the following approach :

This problem can be solved with help of two pointers. Let the first pointer is l and the second pointer is r. Then for every position l we will move right end r until on the substring si.si + 1… sr it is possible to make no more than k swaps to make this substring beautiful. Then we need to update the answer with length of this substring and move l to the right.

First try to solve this ques using this approach. If still you are unable to write code then use the following code. But first give it a try.