Minimum number of Parentheses to be added to make it valid | Java 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
public class GFG { static int minParentheses ( String p ) { int bal = 0 ; int ans = 0 ; for ( int i = 0 ; i < p . length ( ) ; ++ i ) { bal += p . charAt ( i ) == ' ( ' ? 1 : - 1 ; if ( bal == - 1 ) { ans += 1 ; bal += 1 ; } } return bal + ans ; } public static void main ( String args [ ] ) { String p = " ( ) ) " ; System . out . println ( minParentheses ( p ) ) ; } }