Length of Longest Balanced Subsequence | Python3 program to find length of the longest balanced subsequence ; Considering all balanced substrings of length 2 ; Considering all other substrings ; Driver Code
def maxLength ( s , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' and s [ i + 1 ] == ' ) ' ) : NEW_LINE INDENT dp [ i ] [ i + 1 ] = 2 NEW_LINE DEDENT DEDENT for l in range ( 2 , n ) : NEW_LINE INDENT i = - 1 NEW_LINE for j in range ( l , n ) : NEW_LINE INDENT i += 1 NEW_LINE if ( s [ i ] == ' ( ' and s [ j ] == ' ) ' ) : NEW_LINE INDENT dp [ i ] [ j ] = 2 + dp [ i + 1 ] [ j - 1 ] NEW_LINE DEDENT for k in range ( i , j ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k + 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ 0 ] [ n - 1 ] NEW_LINE DEDENT s = " ( ) ( ( ( ( ( ( ) " NEW_LINE n = len ( s ) NEW_LINE print ( maxLength ( s , n ) ) NEW_LINE