text: Minimum number of bracket reversals needed to make an expression balanced | Set | C ++ program to find minimum number of reversals required to balance an expression ; Returns count of minimum reversals for making expr balanced . Returns - 1 if expr cannot be balanced . ; length of expression must be even to make it balanced by using reversals . ; To store number of reversals required . ; To store number of unbalanced opening brackets . ; To store number of unbalanced closing brackets . ; If current bracket is open then increment open count . ; If current bracket is close , check if it balances opening bracket . If yes then decrement count of unbalanced opening bracket else increment count of closing bracket . ; For the case : " } { " or when one closing and one opening bracket remains for pairing , then both need to be reversed . ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinReversals ( string expr ) { int len = expr . length ( ) ; if ( len % 2 ) return -1 ; int ans = 0 ; int i ; int open = 0 ; int close = 0 ; for ( i = 0 ; i < len ; i ++ ) { if ( expr [ i ] == ' { ' ) open ++ ; else { if ( ! open ) close ++ ; else open -- ; } } ans = ( close / 2 ) + ( open / 2 ) ; close %= 2 ; open %= 2 ; if ( close ) ans += 2 ; return ans ; } int main ( ) { string expr = " } } { { " ; cout << countMinReversals ( expr ) ; return 0 ; }