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 . ; Driver Code
< ? php function maxbalancedprefix ( $ str , $ n ) { $ sum = 0 ; $ maxi = 0 ; for ( $ 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 ; } $ str = array ( ' ( ' , ' ( ' , ' ( ' , ' ) ' , ' ( ' , ' ) ' , ' ) ' , ' ( ' , ' ) ' , ' ) ' , ' ( ' , ' ( ' ) ; $ n = count ( $ str ) ; echo maxbalancedprefix ( $ str , $ n ) ; ? >