SanketAndStrings


please can you explain step by step, as it is very old doubt

Hello @akb.tech17

Let’s understand this with an example:
Example:
1
abba
Output:
3
Explanation:

l=0: variable to mark the left index and initialized to 0
r=0: variable to mark the right index and initialized to 0
m=0: to store the perfectness and initialised to zero
t=k: to keep track of the number of replacements we can perform at any instance of time.

  1. First, we will check for the string of character β€˜a’:

    character at a[r] is β€˜a’, increment r
    r:1
    the character at a[r] is not β€˜a’ and t>0, increment r and decrement t as we can replace one β€˜b’ to β€˜a’
    t:0 r:2
    the character at a[r] is not β€˜a’ and t==0. So, we cannot replace. Thus replace m by max. of m and r-l.
    Repeat, while t==0:
    A. if a[l]!=β€˜a’: increment t (because we must have done one replacement for this before and now as we are not considering this character so we can use this replacement somewhere else.)
    B. increment l for each iteration of the loop.
    m:2 t:0 l:1 t:1 l:2
    the character at a[r] is not β€˜a’ and t>0, increment r and decrement t as we can replace one β€˜b’ to β€˜a’
    t:0 r:3
    character at a[r] is β€˜a’, increment r
    r:4
    replace m by max. of m and r-l.
    m:2

l=0: variable to mark the left index and initialized to 0
r=0: variable to mark the right index and initialized to 0
m=0: to store the perfectness and initialised to zero
t=k: to keep track of the number of replacements we can perform at any instance of time.

  1. Now, we will check for the string of character β€˜b’:

    the character at a[r] is not β€˜b’ and t>0, increment r and decrement t as we can replace one β€˜a’ to β€˜b’
    t:0 r:1
    character at a[r] is β€˜b’, increment r
    r:2
    character at a[r] is β€˜b’, increment r
    r:3
    the character at a[r] is not β€˜b’ and t==0. So, we cannot replace. Thus replace m by max. of m and r-l.
    Repeat, while t==0:
    A. if a[l]!=β€˜b’: increment t (because we must have done one replacement for this before and now as we are not considering this character so we can use this replacement somewhere else.)
    B. increment l for each iteration of the loop.
    m:3 t:1 l:1
    the character at a[r] is not β€˜b’ and t>0, increment r and decrement t as we can replace one β€˜a’ to β€˜b’
    t:0 r:4
    replace m by max. of m and r-l.
    m:3
    Hence, the output is m:
    3

Hope, this would help.
Give a like if you are satisfied.

Hope, this would help.
Give a like if you are satisfied.

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.