text: Cost to Balance the parentheses | javascript 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: function costToBalance ( s ) { if ( s . length == 0 ) document . write ( 0 ) ; var ans = 0 ; var o = 0 , c = 0 ; for ( var i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == ' ' ) o ++ ; if ( s [ i ] == ' ' ) c ++ ; } if ( o != c ) return - 1 ; var a = new Array ( s . Length ) ; if ( s [ 0 ] == ' ' ) a [ 0 ] = 1 ; else a [ 0 ] = - 1 ; if ( a [ 0 ] < 0 ) ans += Math . abs ( a [ 0 ] ) ; for ( var 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 ; } var s ; s = " " ; document . write ( costToBalance ( s ) + " " ) ; s = " " ; document . write ( costToBalance ( s ) + " " ) ;