Whats wrong with my code

#include <iostream>
using namespace std;

int main()
{
    
    int n;
    cin >> n;
    string a;
    cin >> a;
    int l = 0;
    int ans = 0;
    int count[2] = {0};
    for (int i = 0; i < a.length(); i++)
    {   int flag=0;
        if (a[i] == 'a')
        {
            count[0]++;
        }
        else
        {
            count[1]++;
        }
        if (count[0] > n or count[1] > n)
        {    flag=1;
            int index = 0;
            if (count[0] > n)
            {
                index = 0;
            }
            else
            {
                index = 1;
            }

            for (int k = i + 1; k < a.length(); k++)
            {
               
             if (a[k] - 'a' != index)
                {
                    ans++;
                }
                else
                {   
                    break;
                }
            }
        }
        if (flag==0)
        {
            ans++;
        }
    }
    cout<<ans;
    return 0;
}


u can simply do it this way

if u dont understand ping back

firstly please explain me to logic in detail please that you have used in your code and please explain my we have two pointers?? ans why we dont updated ans to 0 in if (min(freq[0], freq[1]) > k)

i have tried to explain it with figure

this is a 2 pointer based approach were we expan the window in the right side till the time atmax k swaps can be done
and then
shrink from left ( ie the left pointer ) when we encounter
min( freq[a], freq[b] ) > K i e k swaps have already been carried out

in that case we decrement the freq of element on the left most edge and do left++
else we increase the max possible len of window ( ie ans++)

In this function why all test cases pass when i do right<s.length()-1 and one test case fail if i do right<s.length(). @chhavibansal

for (right; right < s.length()-1; right++)
   {
       if (s[right]!=ch)
       {
           count++;
       }
       if (count==n)
       {
           break;
       }
   }

this is complete code https://ide.codingblocks.com/s/271209

image
check if right < sz of string only then entire while loop