Length of longest balanced parentheses prefix | CPP Program to find length of longest balanced parentheses prefix . ; Return the length of longest balanced parentheses prefix . ; Traversing the string . ; If open bracket add 1 to sum . ; If closed bracket subtract 1 from sum ; if first bracket is closing bracket then this condition would help ; If sum is 0 , store the index value . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxbalancedprefix ( char str [ ] , int n ) { int sum = 0 ; int maxi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) sum += 1 ; else sum -= 1 ; if ( sum < 0 ) break ; if ( sum == 0 ) maxi = i + 1 ; } return maxi ; } int main ( ) { char str [ ] = " ( ( ( ) ( ) ) ( ) ) ( ( " ; int n = strlen ( str ) ; cout << maxbalancedprefix ( str , n ) << endl ; return 0 ; }