#include using namespace std; typedef long long LL; int main() { #ifndef ONLINE_JUDGE freopen("data/data1.in", "r", stdin); // freopen("data/data1.out", "w", stdout); #endif int n; string s; cin >> n >> s; LL l = 0; LL r = 0; vector> lr; LL ans = 0; LL C = 0; for (int i = 0; i < n; i++) { if (s[i] == '(') { l++; } else { if (l > 0) { l--; C++; } else r++; } lr.emplace_back(l, r); ans += C * 2; } sort(lr.begin(), lr.end(), [](auto a, auto b) { return minmax(-a.second, -a.second + a.first - b.second) > minmax(-b.second, -b.second + b.first - a.second); }); l = 0; for (auto p : lr) { LL take = min(l, p.second); l -= take; ans += take * 2; l += p.first; } cout << ans << endl; }