#include #include #include #include using namespace std; int main() { int n; string s; cin >> n >> s; int l = 0; int r = 0; vector> lr; long long ans = 0; long long C = 0; for (int i = 0; i < n; i++) { if (s[i] == '(') { r++; } else { if (r > 0) { r--; C++; } else { l++; } } lr.emplace_back(l, r); ans += C * 2; } sort(lr.begin(), lr.end(), [](auto a, auto b) { return a.second - a.first > b.second - b.first; }); r = 0; for (auto p : lr) { int take = min(r, p.first); r -= take; ans += take * 2; r += p.second; } cout << ans << endl; }