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
function maxbalancedprefix ( str , n ) { var sum = 0 ; var maxi = 0 ; for ( var 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 ; } var str = " " ; var n = str . length ; document . write ( maxbalancedprefix ( str , n ) ) ;