# Cost to Balance the parentheses in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to find the cost to balance the parentheses.

For this we will be provided with a sequence of brackets. Our task is to balance those parentheses in the equation by shifting their position by one and print -1 if balancing them isn’t possible.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int costToBalance(string s) {
if (s.length() == 0)
cout << 0 << endl;
//storing count of opening and
//closing parentheses
int ans = 0;
int o = 0, c = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(')
o++;
if (s[i] == ')')
c++;
}
if (o != c)
return -1;
int a[s.size()];
if (s == '(')
a = 1;
else
a = -1;
if (a < 0)
ans += abs(a);
for (int 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 += abs(a[i]);
}
return ans;
}
int main(){
string s;
s = ")))(((";
cout << costToBalance(s) << endl;
s = "))((";
cout << costToBalance(s) << endl;
return 0;
}

## Output

9
4