text: Minimum Cost required to generate a balanced Bracket Sequence | C # program to implement the above approach ; 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 ; Print the result ; Driver Code
code: using System ; class GFG { static void minCost ( String str , int a , int b ) { int openUnbalanced = 0 ; int closedUnbalanced = 0 ; int openCount = 0 ; int closedCount = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( str [ i ] == ' ( ' ) { openUnbalanced ++ ; openCount ++ ; } else { if ( openUnbalanced == 0 ) closedUnbalanced ++ ; else openUnbalanced -- ; closedCount ++ ; } } int result = a * ( Math . Abs ( openCount - closedCount ) ) ; if ( closedCount > openCount ) closedUnbalanced -= ( closedCount - openCount ) ; if ( openCount > closedCount ) openUnbalanced -= ( openCount - closedCount ) ; result += Math . Min ( a * ( openUnbalanced + closedUnbalanced ) , b * closedUnbalanced ) ; Console . Write ( result + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { String str = " ) ) ( ) ( ( ) ( ) ( " ; int A = 1 , B = 3 ; minCost ( str , A , B ) ; } }