text: Concatenate strings in any order to get Maximum Number of " AB " | Function to find maximum number of ABs ; variable A , B , AB for count strings that end with ' A ' but not end with ' B ' , ' B ' but does not end with ' A ' and ' B ' and ends with ' A ' respectively . ; ' AB ' is already present in string before concatenate them ; count of strings that begins with ' B ' and ends with 'A ; count of strings that begins with ' B ' but does not end with 'A ; count of strings that ends with ' A ' but not end with 'B ; updating the value of ans and add extra count of 'AB ; Driver Code
code: def maxCountAB ( s , n ) : NEW_LINE INDENT A = 0 NEW_LINE B = 0 NEW_LINE BA = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT S = s [ i ] NEW_LINE L = len ( S ) NEW_LINE for j in range ( L - 1 ) : NEW_LINE INDENT if ( S [ j ] == ' A ' and S [ j + 1 ] == ' B ' ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if ( S [ 0 ] == ' B ' and S [ L - 1 ] == ' A ' ) : NEW_LINE INDENT BA += 1 NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT elif ( S [ 0 ] == ' B ' ) : NEW_LINE INDENT B += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT elif ( S [ L - 1 ] == ' A ' ) : NEW_LINE INDENT A += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( BA == 0 ) : NEW_LINE INDENT ans += min ( B , A ) NEW_LINE DEDENT elif ( A + B == 0 ) : NEW_LINE INDENT ans += BA - 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += BA + min ( B , A ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = [ " ABCA " , " BOOK " , " BAND " ] NEW_LINE n = len ( s ) NEW_LINE print ( maxCountAB ( s , n ) ) NEW_LINE DEDENT