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
def countMinMoves ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE a = [ 0 for i in range ( n ) ] NEW_LINE j , ans , sum = 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ' ) ' ) : NEW_LINE INDENT a [ i ] += sum - 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] += sum + 1 NEW_LINE DEDENT sum = a [ i ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i - 1 NEW_LINE while ( i < n and a [ i ] != 0 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( i < n and a [ i - 1 ] < 0 ) : NEW_LINE INDENT ans += i - j NEW_LINE if ( j == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : str = " ) ( ( ) " NEW_LINE INDENT countMinMoves ( str ) NEW_LINE DEDENT