Length of Longest Balanced Subsequence | Python3 program to find length of the longest balanced subsequence ; Variable to count all the open brace that does not have the corresponding closing brace . ; To count all the close brace that does not have the corresponding open brace . ; Iterating over the String ; Number of open braces that hasn 't been closed yet. ; Number of close braces that cannot be mapped to any open brace . ; Mapping the ith close brace to one of the open brace . ; Driver Code
def maxLength ( s , n ) : NEW_LINE INDENT invalidOpenBraces = 0 ; NEW_LINE invalidCloseBraces = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT invalidOpenBraces += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( invalidOpenBraces == 0 ) : NEW_LINE INDENT invalidCloseBraces += 1 NEW_LINE DEDENT else : NEW_LINE INDENT invalidOpenBraces -= 1 NEW_LINE DEDENT DEDENT DEDENT return ( n - ( invalidOpenBraces + invalidCloseBraces ) ) NEW_LINE DEDENT s = " ( ) ( ( ( ( ( ( ) " NEW_LINE n = len ( s ) NEW_LINE print ( maxLength ( s , n ) ) NEW_LINE