text: Cost to Balance the parentheses | C # 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
code: using System ; class GFG { static int costToBalance ( string s ) { if ( s . Length == 0 ) Console . WriteLine ( 0 ) ; int ans = 0 ; int o = 0 , c = 0 ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( s [ i ] == ' ( ' ) o ++ ; if ( s [ i ] == ' ) ' ) c ++ ; } if ( o != c ) return - 1 ; int [ ] a = new int [ s . Length ] ; if ( s [ 0 ] == ' ( ' ) a [ 0 ] = 1 ; else a [ 0 ] = - 1 ; if ( a [ 0 ] < 0 ) ans += Math . Abs ( a [ 0 ] ) ; for ( int i = 1 ; i < s . Length ; i ++ ) { if ( s [ i ] == ' ( ' ) a [ i ] = a [ i - 1 ] + 1 ; else a [ i ] = a [ i - 1 ] - 1 ; if ( a [ i ] < 0 ) ans += Math . Abs ( a [ i ] ) ; } return ans ; } static void Main ( ) { string s ; s = " ) ) ) ( ( ( " ; Console . WriteLine ( costToBalance ( s ) ) ; s = " ) ) ( ( " ; Console . WriteLine ( costToBalance ( s ) ) ; } }