Cost to Balance the parentheses | Python 3 code to calculate the minimum cost to make the given parentheses balanced ; To store absolute count of balanced and unbalanced parenthesis ; o ( open bracket ) stores count of ' ( ' and c ( close bracket ) stores count of ') ; Driver code
def costToBalance ( s ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT ans = 0 NEW_LINE DEDENT ' NEW_LINE INDENT o = 0 NEW_LINE c = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT o += 1 NEW_LINE DEDENT if ( s [ i ] == ' ) ' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( o != c ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT a = [ 0 for i in range ( len ( s ) ) ] NEW_LINE if ( s [ 0 ] == ' ( ' ) : NEW_LINE INDENT a [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ 0 ] = - 1 NEW_LINE DEDENT if ( a [ 0 ] < 0 ) : NEW_LINE INDENT ans += abs ( a [ 0 ] ) NEW_LINE DEDENT for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] = a [ i - 1 ] - 1 NEW_LINE DEDENT if ( a [ i ] < 0 ) : NEW_LINE INDENT ans += abs ( a [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : s = " ) ) ) ( ( ( " NEW_LINE INDENT print ( costToBalance ( s ) ) s = " ) ) ( ( " NEW_LINE print ( costToBalance ( s ) ) NEW_LINE DEDENT