Minimum Cost required to generate a balanced Bracket Sequence | Function to calculate the minimum cost required to generate a balanced bracket sequence ; Stores the count of unbalanced open brackets ; Stores the count of unbalanced closed brackets ; Stores the count of open brackets ; Stores the count of closed brackets ; If open brace is encountered ; Otherwise ; If no unbalanced open brackets are present ; Increase count of unbalanced closed brackets ; Otherwise ; Reduce count of unbalanced open brackets ; Increase count of closed brackets ; Calculate lower bound of minimum cost ; Reduce excess open or closed brackets to prevent counting them twice ; Update answer by adding minimum of removing both unbalanced open and closed brackets or inserting closed unbalanced brackets to end of String ; Prthe result ; Driver Code
def minCost ( str , a , b ) : NEW_LINE INDENT openUnbalanced = 0 ; NEW_LINE closedUnbalanced = 0 ; NEW_LINE openCount = 0 ; NEW_LINE closedCount = 0 ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT openUnbalanced += 1 ; NEW_LINE openCount += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( openUnbalanced == 0 ) : NEW_LINE INDENT closedUnbalanced += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT openUnbalanced -= 1 ; NEW_LINE DEDENT closedCount += 1 ; NEW_LINE DEDENT DEDENT result = a * ( abs ( openCount - closedCount ) ) ; NEW_LINE if ( closedCount > openCount ) : NEW_LINE INDENT closedUnbalanced -= ( closedCount - openCount ) ; NEW_LINE DEDENT if ( openCount > closedCount ) : NEW_LINE INDENT openUnbalanced -= ( openCount - closedCount ) ; NEW_LINE DEDENT result += min ( a * ( openUnbalanced + closedUnbalanced ) , b * closedUnbalanced ) ; NEW_LINE print ( result ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : str = " ) ) ( ) ( ( ) ( ) ( " ; NEW_LINE INDENT A = 1 ; B = 3 ; NEW_LINE minCost ( str , A , B ) ; NEW_LINE DEDENT