Considering all other substrings
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