Minimize cost to rearrange substrings to convert a string to a Balanced Bracket Sequence | Function to count minimum number of operations to convert the string to a balanced bracket sequence ; Initialize the integer array ; Traverse the string ; Decrement a [ i ] ; Increment a [ i ] ; Update the sum as current value of arr [ i ] ; If answer exists ; Traverse from i ; Find all substrings with 0 sum ; Print the sum of sizes ; No answer exists ; Driver Code
function countMinMoves ( str ) { var n = str . length ; var a = Array ( n ) . fill ( 0 ) ; var j , ans = 0 , i , sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ' ) { a [ i ] += sum - 1 ; } else { a [ i ] += sum + 1 ; } sum = a [ i ] ; } if ( sum == 0 ) { i = 1 ; while ( i < n ) { j = i - 1 ; while ( i < n && a [ i ] != 0 ) i ++ ; if ( i < n && a [ i - 1 ] < 0 ) { ans += i - j ; if ( j == 0 ) ans ++ ; } i ++ ; } document . write ( ans + " " ) ; } else document . write ( " " ) ; } var str = " " ; countMinMoves ( str ) ;