Maximum length of balanced string after swapping and removal of characters | Function to return the length of the longest balanced sub - string ; To store the count of parentheses ; Traversing the string ; Check type of parentheses and incrementing count for it ; Sum all pair of balanced parentheses ; Driven code
def maxBalancedStr ( s ) : NEW_LINE INDENT open1 = 0 NEW_LINE close1 = 0 NEW_LINE open2 = 0 NEW_LINE close2 = 0 NEW_LINE open3 = 0 NEW_LINE close3 = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : open1 += 1 continue if s [ i ] == ' ) ' : NEW_LINE INDENT close1 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' { ' : NEW_LINE INDENT open2 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' } ' : NEW_LINE INDENT close2 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' [ ' : NEW_LINE INDENT open3 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' ] ' : NEW_LINE INDENT close3 += 1 NEW_LINE continue NEW_LINE DEDENT DEDENT maxLen = ( 2 * min ( open1 , close1 ) + 2 * min ( open2 , close2 ) + 2 * min ( open3 , close3 ) ) NEW_LINE return maxLen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : s = " ) ) [ ] ] ( ( " NEW_LINE INDENT print ( maxBalancedStr ( s ) ) NEW_LINE DEDENT