Length of longest balanced parentheses prefix | Function to 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
def maxbalancedprefix ( str , n ) : NEW_LINE INDENT _sum = 0 NEW_LINE maxi = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if str [ i ] == ' ( ' : NEW_LINE INDENT _sum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT _sum -= 1 NEW_LINE DEDENT if _sum < 0 : NEW_LINE INDENT break NEW_LINE DEDENT if _sum == 0 : NEW_LINE INDENT maxi = i + 1 NEW_LINE DEDENT DEDENT return maxi NEW_LINE DEDENT str = ' ( ( ( ) ( ) ) ( ) ) ( ( ' NEW_LINE n = len ( str ) NEW_LINE print ( maxbalancedprefix ( str , n ) ) NEW_LINE