n = int(input()) s = input() # Preprocess each prefix's L, R, balance, and min_balance L = [] R = [] balance_list = [] min_balance_list = [] current_L = 0 current_R = 0 balance = 0 min_balance = 0 for c in s: if c == '(': current_L += 1 balance += 1 else: current_R += 1 balance -= 1 L.append(current_L) R.append(current_R) balance_list.append(balance) min_balance = min(min_balance, balance) min_balance_list.append(min_balance) # Prepare list of prefixes with their min_balance, balance, L, R prefixes = [] for i in range(n): min_b = min_balance_list[i] bal = balance_list[i] l = L[i] r = R[i] prefixes.append((min_b, bal, l, r)) # Sort prefixes by min_b descending, then bal descending prefixes.sort(key=lambda x: (-x[0], -x[1])) # Process the sorted prefixes to compute global_min and current_balance current_balance = 0 global_min = 0 for p in prefixes: min_b, bal, l, r = p new_balance = current_balance + bal new_global_min = min(global_min, current_balance + min_b) global_min = new_global_min current_balance = new_balance # Compute total_L and total_R total_L = sum(L) total_R = sum(R) # Compute the answer if global_min >= 0: ans = 2 * min(total_L, total_R) else: effective = max(min(total_L, total_R) + global_min, 0) ans = 2 * effective print(ans)