Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2 | C ++ implementation of the approach ; Function that returns true if the string can be balanced ; Count to check the difference between the frequencies of ' ( ' and ' ) ' and count_1 is to find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; Traverse the given string ; Increase the count ; Decrease the count ; Find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; If the minimum difference is greater than or equal to - 1 and the overall difference is zero ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeBalanced ( string s , int n ) { int count = 0 , count_1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) count ++ ; else count -- ; count_1 = min ( count_1 , count ) ; } if ( count_1 >= -1 && count == 0 ) return true ; return false ; } int main ( ) { string s = " ( ) ) ( ) ( " ; int n = s . length ( ) ; if ( canBeBalanced ( s , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }