Minimum number of Parentheses to be added to make it valid | C ++ Program to find minimum number of ' ( ' or ' ) ' must be added to make Parentheses string valid . ; Function to return required minimum number ; maintain balance of string ; It is guaranteed bal >= - 1 ; Driver code ; Function to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minParentheses ( string p ) { int bal = 0 ; int ans = 0 ; for ( int i = 0 ; i < p . length ( ) ; ++ i ) { bal += p [ i ] == ' ( ' ? 1 : -1 ; if ( bal == -1 ) { ans += 1 ; bal += 1 ; } } return bal + ans ; } int main ( ) { string p = " ( ) ) " ; cout << minParentheses ( p ) ; return 0 ; }