#include #include #include using namespace std; int n, l, r, ans; string s; struct Node { int L, R; }; vector nodes; int main() { scanf("%d", &n); cin >> s; for (int i = 0, match = 0; i < s.size(); ++i) { if (s[i] == '(') { ++l; } else { if (l > 0) { ++match; --l; } else { ++r; } } ans += match * 2; nodes.push_back({ l, r }); } sort(nodes.begin(), nodes.end(), [](Node n1, Node n2) { bool n1_type = n1.R <= n1.L, n2_type = n2.R <= n2.L; if (n1_type != n2_type) return n1_type; if (n1.R <= n1.L) return n1.R < n2.R; return n1.L > n2.L; }); l = 0LL; for (auto node : nodes) { int match = min(l, node.R); l -= match; l += node.L; ans += match * 2; } printf("%d\n", ans); return 0; }