/* Author:bhagatsunny96
         JGEC
	   template__
	lets_code_it_ */
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define ll long long int
#define ld long double
#define fi first
#define se second
#define mod 1000000007
#define test long long int t; cin>>t; while(t-->0)
#define fIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define loop(n) for(long long int i=0;i<n;i++)
#define loopr(n) for(long long int i=n-1;i>=0;i--)
#define lrp(a,b) for(long long int i=a;i<=b;i++)
#define lrn(a,b) for(long long int i=b;i>=a;i--)
#define endl '\n'
#define vec vector<ll>v;
#define imap map<ll,ll>mip;
#define umap unordered_map<ll,ll>ump;
#define sett set<ll>st;
using namespace std;
ll gcd(ll a, ll b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b)
 {
    return (a*b)/__gcd(a, b);
 }
 ll power(ll x, unsigned ll y)
 {
    ll temp;
    if( y == 0)
        return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
 }
 bool isPrime(ll num)
 {
    bool flag=true;
    for(ll i =2;i<=num/2;i++)
    {
       if(num%i==0)
       {
          flag=false;
          break;
       }
    }
    return flag;
}
bool isPalin(ll num)
{
    bool flag=false;
    ll digit,rev=0,n=num;
    do
     {
         digit = num % 10;
         rev = (rev * 10) + digit;
         num = num / 10;
     } while (num != 0);
     if(rev==n)
     flag=true;
     return flag;
}
ll sumofdigits(ll n)
{
    ll c=0;
    while(n>0)
    {
        c++;
        n/=10;
    }
    return c;
}
bool sortinrev(const pair<int,int>&a,const pair<int,int>&b)
{
    return (a.first > b.first);
}
bool sortbysec(const pair<int,int> &a, const pair<int,int> &b)
{
    return (a.second < b.second);
}
string sortString(string &str)
{
   sort(str.begin(), str.end());
   return str;
}
void countSort(ll arr[], ll n, ll exp)
{
	ll output[n];
	ll i, count[10] = {0};
	for (i = 0; i < n; i++)
		count[ (arr[i]/exp)%10 ]++;
	for (i = 1; i < 10; i++)
		count[i] += count[i - 1];
	for (i = n - 1; i >= 0; i--)
	{
		output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
		count[ (arr[i]/exp)%10 ]--;
	}
	for (i = 0; i < n; i++)
		arr[i] = output[i];
}
void radixsort(ll arr[], ll n)
{
    ll mx = arr[0];
	for (ll i = 1; i < n; i++)
		if (arr[i] > mx)
			mx = arr[i];
	ll m =mx;
	for (ll exp = 1; m/exp > 0; exp *= 10)
		countSort(arr, n, exp);
}
void print(ll arr[], ll n)
{
    for (ll i = 0; i < n; i++)
        cout << arr[i] << " ";
}
int main()
{
    fIO
    ll n;
    cin>>n;
    string s;
    cin>>s;
    ll ans=0;
    else
    {
        list<char>sl;
        ll cnt=0;
        ll p=-1;
        ll ans=0;
        loop(n)
        {
            if(s[i]==')')
            {
                if(sl.size()!=0)
                {
                    if(sl.back()=='(')
                    sl.pop_front();
                    else
                    sl.push_back(')');
                }
                else
                sl.push_back(')');
            }
            else
            {
                if(sl.size()!=0)
                {
                    if(sl.back()=='(')
                    {
                        sl.push_back('(');
                    }
                    else
                    {
                        sl.pop_front();
                        ans+=2;
                    }
                }
                else
                {
                    sl.push_back('(');
                }
            }
        }
        if(sl.size()!=0)
        cout<<-1<<endl;
        else
        cout<<ans<<endl;
    }
	return 0;
}


/* Author:bhagatsunny96
         JGEC
	   template__
	lets_code_it_ */
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define ll long long int
#define ld long double
#define fi first
#define se second
#define mod 1000000007
#define test long long int t; cin>>t; while(t-->0)
#define fIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define loop(n) for(long long int i=0;i<n;i++)
#define loopr(n) for(long long int i=n-1;i>=0;i--)
#define lrp(a,b) for(long long int i=a;i<=b;i++)
#define lrn(a,b) for(long long int i=b;i>=a;i--)
#define endl '\n'
#define vec vector<ll>v;
#define imap map<ll,ll>mip;
#define umap unordered_map<ll,ll>ump;
#define sett set<ll>st;
using namespace std;
ll gcd(ll a, ll b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b)
 {
    return (a*b)/__gcd(a, b);
 }
 ll power(ll x, unsigned ll y)
 {
    ll temp;
    if( y == 0)
        return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
 }
 bool isPrime(ll num)
 {
    bool flag=true;
    for(ll i =2;i<=num/2;i++)
    {
       if(num%i==0)
       {
          flag=false;
          break;
       }
    }
    return flag;
}
bool isPalin(ll num)
{
    bool flag=false;
    ll digit,rev=0,n=num;
    do
     {
         digit = num % 10;
         rev = (rev * 10) + digit;
         num = num / 10;
     } while (num != 0);
     if(rev==n)
     flag=true;
     return flag;
}
ll sumofdigits(ll n)
{
    ll c=0;
    while(n>0)
    {
        c++;
        n/=10;
    }
    return c;
}
bool sortinrev(const pair<int,int>&a,const pair<int,int>&b)
{
    return (a.first > b.first);
}
bool sortbysec(const pair<int,int> &a, const pair<int,int> &b)
{
    return (a.second < b.second);
}
string sortString(string &str)
{
   sort(str.begin(), str.end());
   return str;
}
void countSort(ll arr[], ll n, ll exp)
{
	ll output[n];
	ll i, count[10] = {0};
	for (i = 0; i < n; i++)
		count[ (arr[i]/exp)%10 ]++;
	for (i = 1; i < 10; i++)
		count[i] += count[i - 1];
	for (i = n - 1; i >= 0; i--)
	{
		output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
		count[ (arr[i]/exp)%10 ]--;
	}
	for (i = 0; i < n; i++)
		arr[i] = output[i];
}
void radixsort(ll arr[], ll n)
{
    ll mx = arr[0];
	for (ll i = 1; i < n; i++)
		if (arr[i] > mx)
			mx = arr[i];
	ll m =mx;
	for (ll exp = 1; m/exp > 0; exp *= 10)
		countSort(arr, n, exp);
}
void print(ll arr[], ll n)
{
    for (ll i = 0; i < n; i++)
        cout << arr[i] << " ";
}
int main()
{
    fIO
    ll n;
    cin>>n;
    string s;
    cin>>s;
    ll ans=0;
    if(n%2!=0)
    cout<<-1<<endl;
    else
    {
        ll cnt=0;
        ll p=-1;
        ll ans=0;
        loop(n)
        {
            if(s[0]==')')
            {
                s[0]='(';
            }
            if(s[i]=='(')
            {
                cnt++;
            }
            else
            {
                p=i;
            }
            if(p!=-1 && cnt>1)
            {
                for(ll j=p+1;j<n;j++)
                {
                    if(s[j]=='(' && cnt>=0)
                    {
                        ans++;
                        cnt--;
                        s[j]==')';
                    }
                    else
                    {
                        cnt--;
                    }
                }
            }
        }
        cout<<ans*2<<endl;
    }
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define nl "\n"

ll n,ans;
string s;

bool fun(string p)
{
    ll x = p.size();
    stack<char> ss;
    int zz=0;

    for(ll i=0; i<x; i++)
    {
        if((p[i]==')') && (ss.empty())) {zz=1; break;}
        if((p[i]==')') && (ss.top()!='(')) {zz=1; break;}
        else if(p[i]=='(') ss.push(p[i]);
        else ss.pop();
    }
    if(ss.size()==0 && zz==0)
        return true;
    else return false;
}

void solve()
{
    cin>>n>>s;
    ll a=0,b=0,c=0,d=0;

    for(ll i=0; i<n; i++)
    {
        if(s[i]=='(') a++;
        else b++;
    }
    if(a!=b) cout<<-1;
    else
    {

    if(fun(s)==true) {cout<<0;}
    else
    {

    string p="";
    for(ll i=0; i<n; i++)
    {

        if(s[i]=='(') { c++; p+=s[i];}
        else { d++; p+=s[i];}

        if(c==d && c!=0)
        {
            if(fun(p)==false) ans+=p.length();
            p="";
            c=0;
            d=0;

        }

    }

    cout<<ans;

    }
    }

}

int main ()
{
    // ll t; cin>>t;
    // while(t--)
    solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define nl "\n"

ll n,ans;
string s;

bool fun(string p, int c, int d)
{
    int ff=0;
    for(ll i=0; i<c; i++)
    {
        if(p[i]==')') {ff=1; break;}
    }
    if(ff==0) return true;
    return false;
}

void solve()
{
    cin>>n>>s;
    ll a=0,b=0,c=0,d=0;

    for(ll i=0; i<n; i++)
    {
        if(s[i]=='(') a++;
        else b++;
    }
    if(a!=b) cout<<-1;
    else
    {

    string p="";
    for(ll i=0; i<n; i++)
    {

        if(s[i]=='(') { c++; p+=s[i];}
        else { d++; p+=s[i];}

        if(c==d && c!=0)
        {
            if(fun(p,c,d)==false) ans+=p.length();
            p="";
            c=0;
            d=0;

        }

    }

    cout<<ans;

    }
}

int main ()
{
    // ll t; cin>>t;
    // while(t--)
    solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define nl "\n"

ll n,ans;
string s;

bool fun(string p, int c, int d)
{
    int ff=0;
    for(ll i=0; i<c; i++)
    {
        if(p[i]==')') {ff=1; break;}
    }
    if(ff==0) return true;
    return false;
}

void solve()
{
    cin>>n>>s;
    ll a=0,b=0,c=0,d=0;

    for(ll i=0; i<n; i++)
    {
        if(s[i]=='(') a++;
        else b++;
    }
    if(a!=b) cout<<-1;
    else
    {
    stack<char> ss;
    int zz=0;

    for(ll i=0; i<n; i++)
    {
        if((s[i]==')') && (ss.empty())) {zz=1; break;}
        if((s[i]==')') && (ss.top()!='(')) {zz=1; break;}
        else if(s[i]=='(') ss.push(s[i]);
        else ss.pop();
    }
    if(ss.size()==0)
    {
        if(zz==0) cout<<0;

    else
    {

    string p="";
    for(ll i=0; i<n; i++)
    {

        if(s[i]=='(') { c++; p+=s[i];}
        else { d++; p+=s[i];}

        if(c==d && c!=0)
        {
            if(fun(p,c,d)==false) ans+=p.length();
            p="";
            c=0;
            d=0;

        }

    }

    cout<<ans;
    }

    }
    else
    cout<<-1;

    }
}

int main ()
{
    // ll t; cin>>t;
    // while(t--)
    solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define nl "\n"

ll n,ans;
string s;

bool fun(string p, int c, int d)
{
    int ff=0;
    for(ll i=0; i<c; i++)
    {
        if(p[i]==')') {ff=1; break;}
    }
    if(ff==0) return true;
    return false;
}

void solve()
{
    cin>>n>>s;
    ll a=0,b=0,c=0,d=0;

    for(ll i=0; i<n; i++)
    {
        if(s[i]=='(') a++;
        else b++;
    }
    if(a!=b) cout<<-1;
    else
    {
    stack<char> ss;
    int zz=0;

    for(ll i=0; i<n; i++)
    {
        if((s[i]==')') && (ss.empty())) {zz=1; break;}
        if((s[i]==')') && (ss.top()!='(')) {zz=1; break;}
        else if(s[i]=='(') ss.push(s[i]);
        else ss.pop();
    }

    if(zz==0) cout<<0;

    else
    {

    string p="";
    for(ll i=0; i<n; i++)
    {

        if(s[i]=='(') { c++; p+=s[i];}
        else { d++; p+=s[i];}

        if(c==d && c!=0)
        {
            if(fun(p,c,d)==false) ans+=p.length();
            p="";
            c=0;
            d=0;

        }

    }

    cout<<ans;
    }

    }
}

int main ()
{
    // ll t; cin>>t;
    // while(t--)
    solve();
    return 0;
}


#include <bits/stdc++.h>

#define Zero_IQ                   \
    ios_base::sync_with_stdio(0); \
    cin.tie(0);
using namespace std;
typedef unsigned long long ull;
typedef long long ll;

/*int rightt[15], leftt[15];
vector<ll> column(10, 0);
vector<vector<ll>> v(10, vector<ll>(10, 0));
void rec(ll row) {
    for (int i = 0; i < 8; ++i) {
        if (!column[i] && !rightt[row + i] && !leftt[row - i]) {
            column[i] = 1;
            rightt[row+i] = 1;
            leftt[row-i] = 1;
            v[row][i] = 1;
            if (row < 7) {
                rec(row + 1);
            } else {
                for (int j = 0; j < 8; ++j) {
                    for (int k = 0; k < 8; ++k) {
                        cout << v[j][k];
                    }
                    cout << endl;
                }
                cout << endl;
            }
            column[i] = 0;
            rightt[row+i] = 0;
            leftt[row-i] = 0;
            v[row][i] = 0;
        }
    }
}
*/
int main() {
    Zero_IQ
    ll n;
    cin >> n;
    string s;
    cin >> s;
    vector<char> open, closed;
    ll summ = 0;
    ll opens = 0;
    ll closes = 0;
    vector<bool> isfound(s.length() + 1, 0);
    for (int j = 0; j < s.length(); ++j) {
        if (s[j] == '(')opens++;
        else closes++;
    }
    if (opens != closes)return cout << -1 << endl, 0;
    for (int i = 0; i < s.length(); ++i) {
        if (s[i] == ')') {
            closed.push_back(i + 1);
        } else {
            if (!closed.empty()) {
                //cout<<((i+1)-(closed.back()))+1<<endl;
                isfound[i + 1] = true;
                isfound[closed.back()] = true;
                closed.pop_back();
            }
        }
    }
    ll minn = 1e18;
    ll maxx = 0;
    ll c = 0;
    for (ll i = 1; i <= s.length(); i++) {
        if (isfound[i]) {
            c++;
            minn = min(minn, i);
            maxx = max(maxx, i);
        } else if (c) {
            c = 0;
            summ += (maxx - minn) + 1;
            minn = 1e18;
            maxx = 0;
        }
    }
    if (c)summ += (maxx - minn) + 1;
    cout << summ << endl;

    return 0;
}


/*
 *  WATCH THIS
 */
#include <bits/stdc++.h>

using namespace std;
#define endl '\n'

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ll N = 1e6 + 2, NN = 1e3 + 4, oo = INT_MAX, mod = 1e9 + 7;

void debug() { cerr << endl; }

template<typename Head, typename... Tail>
void debug(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug(T...);
}

void Zero_IQ() {
  int n;
  cin >> n;
  string s;
  cin >> s;
  int cnt = 0, res = 0;
  int minn = 1e9;
  for (int i = 0; i < s.length(); ++i) {
    if (s[i] == '(')cnt++;
    else cnt--;
    if (cnt < 0) {
      minn = min(minn, i);
    }
    if (cnt == 0 and minn != 1e9) {
      res += (i - minn) + 1;
      minn = 1e9;
    }
  }
  if (cnt)cout << -1 << endl;
  else cout << res << endl;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  Zero_IQ();
  return 0;
}


#include <bits/stdc++.h>

#define Zero_IQ                   \
    ios_base::sync_with_stdio(0); \
    cin.tie(0);
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
/*int rightt[15], leftt[15];
vector<ll> column(10, 0);
vector<vector<ll>> v(10, vector<ll>(10, 0));
void rec(ll row) {
    for (int i = 0; i < 8; ++i) {
        if (!column[i] && !rightt[row + i] && !leftt[row - i]) {
            column[i] = 1;
            rightt[row+i] = 1;
            leftt[row-i] = 1;
            v[row][i] = 1;
            if (row < 7) {
                rec(row + 1);
            } else {
                for (int j = 0; j < 8; ++j) {
                    for (int k = 0; k < 8; ++k) {
                        cout << v[j][k];
                    }
                    cout << endl;
                }
                cout << endl;
            }
            column[i] = 0;
            rightt[row+i] = 0;
            leftt[row-i] = 0;
            v[row][i] = 0;
        }
    }
}
*/
int main() {
    Zero_IQ
    ll n;
    cin>>n;
    string s;
    cin>>s;
    vector<char>v;
    ll open=0;
    ll closed=0;
    for (int i = 0; i <s.length(); ++i) {
        if(v.empty()) {
            v.push_back(s[i]);
            if(s[i]=='(')open++;
            else closed++;
          //  cout<<v.size()<<endl;

        }
        else {
            if(v.back()=='('&&s[i]==')'){
                v.pop_back();
                open--;
            }
            else {
                v.push_back(s[i]);
                if(s[i]=='(')open++;
                else closed++;
            }
            //cout<<v.size()<<endl;

        }
    }
    if(open!=closed){
        cout<<-1<<endl;
    }
    else {
        ll q=v.size();
       // cout<<q;
        ll summ=0;
        while(q!=0){
            summ+=q;
            q-=2;
        }
        cout<<summ<<endl;
    }
    return 0;
}


/*
 *  WATCH THIS
 */
#include <bits/stdc++.h>

using namespace std;
#define endl '\n'

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ll N = 1e6 + 2, NN = 1e3 + 4, oo = INT_MAX, mod = 1e9 + 7;

void debug() { cerr << endl; }

template<typename Head, typename... Tail>
void debug(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug(T...);
}

void يارب() {
  int n;
  cin >> n;
  string s;
  cin >> s;
  int cnt = 0, res = 0;
  int minn = 1e9;
  for (int i = 0; i < s.length(); ++i) {
    if (s[i] == '(')cnt++;
    else cnt--;
    if (cnt < 0) {
      minn = min(minn, i);
    }
    if (cnt == 0 and minn != 1e9) {
      res += (i - minn) + 1;
      minn = 1e9;
    }
  }
  if (cnt)cout << -1 << endl;
  else cout << res << endl;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  يارب();
  return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//using namespace __gnu_pbds;
#define fastio() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb  push_back
#define show(x) cout<<(#x)<<" : "<<x<<endl;
#define ll  long long
#define ld  long double
#define fill(a,val) memset(a,val,sizeof(a))
#define mp  make_pair
#define ff  first
#define ss  second
#define pii pair<ll,ll>
#define sq(x) ((x)*(x))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define endl "\n"
#define int long long
#define in(a) cin>>a;
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
const ll MOD     = 1000*1000*1000+7;
const ll INF     = 1ll*1000*1000*1000*1000*1000*1000 + 7;
const ll MOD2    = 998244353;
const ll N       = 1000 * 100 + 10;
const ll N2      = 70;
const ld PI  = 3.141592653589793;
//template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p = LLONG_MAX ){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
ll lcm(ll a , ll b){return (a*b)/gcd(a,b);}
void solve(){
  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
  #endif
}
signed main()
{
    fastio();
    //cout<<fixed<<setprecision(20);
    //CHECK for LONG LONG and LONG DOUBLE
    //*comment for all except cc/cf
    ll n;
    cin>>n;
    string s;
    cin>>s;
    ll s=0,l=0;
    for(ll i=0;i<n;i++){
      if(s[i]==')') l++;
      else{
       l--;
       if(l>=0) sum++;
      }
     }
     ll ans;
     if(l!=0){
       ans=-1;
     }
     else{
      ans=2*l;
     }
     cout<<ans<<endl;
    }
    //printclock;
    return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//using namespace __gnu_pbds;
#define fastio() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb  push_back
#define show(x) cout<<(#x)<<" : "<<x<<endl;
#define ll  long long
#define ld  long double
#define fill(a,val) memset(a,val,sizeof(a))
#define mp  make_pair
#define ff  first
#define ss  second
#define pii pair<ll,ll>
#define sq(x) ((x)*(x))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define endl "\n"
#define int long long
#define in(a) cin>>a;
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
const ll MOD     = 1000*1000*1000+7;
const ll INF     = 1ll*1000*1000*1000*1000*1000*1000 + 7;
const ll MOD2    = 998244353;
const ll N       = 1000 * 100 + 10;
const ll N2      = 70;
const ld PI  = 3.141592653589793;
//template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p = LLONG_MAX ){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
ll lcm(ll a , ll b){return (a*b)/gcd(a,b);}
void solve(){
  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
  #endif
}
signed main()
{
    fastio();
    //cout<<fixed<<setprecision(20);
    //CHECK for LONG LONG and LONG DOUBLE
    //*comment for all except cc/cf
    ll n;
    cin>>n;
    string s;
    cin>>s;
    stack<char> p;
     for(ll i=0;i<n;i++){
      if(p.size()==0){
        p.push(s[i]);
      }
      else if(s[i]=='('){
        p.push(s[i]);
      }
      else{
       if(p.top()=='('){
         p.pop();
         p.push('a');
       }
       else{
        p.push(s[i]);
       }
      }
     }
     ll ans=0;
     ll co=0,cc=0,fl=1;
     while(p.size()>0){
      if(p.top()=='a'){
        if(co!=cc){
          fl=0;
          break;
        }
        ans+=(co+cc);
        co=0,cc=0;
        p.pop();
      }
      else{
       if(p.top()=='('){
         co++;
       }
       else{
         cc++;
       }
       p.pop();
      }
     }
     if(co!=cc){
       fl=0;
     }
     else{
      ans+=(co+cc);
     }
     if(fl==0){
       cout<<-1<<endl;
     }
     else{
      cout<<ans<<endl;
     }
    //printclock;
    return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//using namespace __gnu_pbds;
#define fastio() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb  push_back
#define show(x) cout<<(#x)<<" : "<<x<<endl;
#define ll  long long
#define ld  long double
#define fill(a,val) memset(a,val,sizeof(a))
#define mp  make_pair
#define ff  first
#define ss  second
#define pii pair<ll,ll>
#define sq(x) ((x)*(x))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define endl "\n"
#define int long long
#define in(a) cin>>a;
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
const ll MOD     = 1000*1000*1000+7;
const ll INF     = 1ll*1000*1000*1000*1000*1000*1000 + 7;
const ll MOD2    = 998244353;
const ll N       = 1000 * 100 + 10;
const ll N2      = 70;
const ld PI  = 3.141592653589793;
//template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p = LLONG_MAX ){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
ll lcm(ll a , ll b){return (a*b)/gcd(a,b);}
void solve(){
  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
  #endif
}
signed main()
{
    fastio();
    //cout<<fixed<<setprecision(20);
    //CHECK for LONG LONG and LONG DOUBLE
    //*comment for all except cc/cf
    ll n;
    cin>>n;
    string s;
    cin>>s;
    ll p[n];
    fill(p,0);
    if(s[0]=='('){
      p[0]=-1;
    }
    else{
      p[0]=1;
    }
    for(ll i=1;i<n;i++){
      if(s[i]=='('){
        p[i]=p[i-1]-1;
      }
      else{
       p[i]=p[i-1]+1;
      }
    }
    if(p[n-1]!=0){
      cout<<-1;
    }
    else{
     ll p1,p2,ans=0;
     for(ll i=0;i<n;i++){
       if(p[i]==0){
         p1=i;
         for(ll j=(i-1);j>=0;j--){
           if(p[j]!=0){
             p2=i;
           }
         }
         stack<char> u;
         for(ll k=p2;k<=p1;k++){
           if(s[k]=='('){
             u.push(s[k]);
           }
           else{
            if(u.top()=='('){
              u.pop();
            }
            else{
             u.push(s[k]);
            }
           }
         }
           ans+=u.size();
       }
     }
     cout<<ans<<endl;
    }
    //printclock;
    return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//using namespace __gnu_pbds;
#define fastio() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb  push_back
#define show(x) cout<<(#x)<<" : "<<x<<endl;
#define ll  long long
#define ld  long double
#define fill(a,val) memset(a,val,sizeof(a))
#define mp  make_pair
#define ff  first
#define ss  second
#define pii pair<ll,ll>
#define sq(x) ((x)*(x))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define endl "\n"
#define int long long
#define in(a) cin>>a;
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
const ll MOD     = 1000*1000*1000+7;
const ll INF     = 1ll*1000*1000*1000*1000*1000*1000 + 7;
const ll MOD2    = 998244353;
const ll N       = 1000 * 100 + 10;
const ll N2      = 70;
const ld PI  = 3.141592653589793;
//template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p = LLONG_MAX ){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
ll lcm(ll a , ll b){return (a*b)/gcd(a,b);}
void solve(){
  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
  #endif
}
signed main()
{
    fastio();
    //cout<<fixed<<setprecision(20);
    //CHECK for LONG LONG and LONG DOUBLE
    //*comment for all except cc/cf
    ll n;
    cin>>n;
    string s;
    cin>>s;
    ll tot=0,l=0;
    for(ll i=0;i<n;i++){
      if(s[i]==')') l++;
      else{
       l--;
       if(l>=0) tot++;
      }
     }
     ll ans;
     if(l!=0){
       ans=-1;
     }
     else{
      ans=tot*2;
     }
     cout<<ans<<endl;
    //printclock;
    return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//using namespace __gnu_pbds;
#define fastio() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb  push_back
#define show(x) cout<<(#x)<<" : "<<x<<endl;
#define ll  long long
#define ld  long double
#define fill(a,val) memset(a,val,sizeof(a))
#define mp  make_pair
#define ff  first
#define ss  second
#define pii pair<ll,ll>
#define sq(x) ((x)*(x))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define endl "\n"
#define int long long
#define in(a) cin>>a;
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
const ll MOD     = 1000*1000*1000+7;
const ll INF     = 1ll*1000*1000*1000*1000*1000*1000 + 7;
const ll MOD2    = 998244353;
const ll N       = 1000 * 100 + 10;
const ll N2      = 70;
const ld PI  = 3.141592653589793;
//template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p = LLONG_MAX ){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
ll lcm(ll a , ll b){return (a*b)/gcd(a,b);}
void solve(){
  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
  #endif
}
signed main()
{
    fastio();
    //cout<<fixed<<setprecision(20);
    //CHECK for LONG LONG and LONG DOUBLE
    //*comment for all except cc/cf
    ll n;
    cin>>n;
    char ans[n];
    cin>>ans;
    ans[n]='\0';
    ll an=0,atn=0;
    for(ll i=0;i<n;i++){
      if(ans[i]==')'){
        atn++;
      }
      else{
       atn--;
       if(atn>=0) an++;
      }
    }
    if(atn!=0){
      cout<<-1;
    }
    else{
     cout<<2*an;
    }
    cout<<endl;
    //printclock;
    return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//using namespace __gnu_pbds;
#define fastio() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb  push_back
#define show(x) cout<<(#x)<<" : "<<x<<endl;
#define ll  long long
#define ld  long double
#define fill(a,val) memset(a,val,sizeof(a))
#define mp  make_pair
#define ff  first
#define ss  second
#define pii pair<ll,ll>
#define sq(x) ((x)*(x))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define endl "\n"
#define int long long
#define in(a) cin>>a;
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
const ll MOD     = 1000*1000*1000+7;
const ll INF     = 1ll*1000*1000*1000*1000*1000*1000 + 7;
const ll MOD2    = 998244353;
const ll N       = 1000 * 100 + 10;
const ll N2      = 70;
const ld PI  = 3.141592653589793;
//template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p = LLONG_MAX ){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
ll lcm(ll a , ll b){return (a*b)/gcd(a,b);}
void solve(){
  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
  #endif
}
signed main()
{
    fastio();
    //cout<<fixed<<setprecision(20);
    //CHECK for LONG LONG and LONG DOUBLE
    //*comment for all except cc/cf
    ll n;
    cin>>n;
    string s;
    cin>>s;
    ll p[n];
    fill(p,0);
    if(s[0]=='('){
      p[0]=-1;
    }
    else{
      p[0]=1;
    }
    for(ll i=1;i<n;i++){
      if(s[i]=='('){
        p[i]=p[i-1]-1;
      }
      else{
       p[i]=p[i-1]+1;
      }
    }
    /*for(ll i=0;i<n;i++){
      cout<<p[i]<<" ";
    }
    cout<<endl;*/
    if(p[n-1]!=0){
      cout<<-1;
    }
    else{
     ll p1,p2,ans=0;
     for(ll i=0;i<n;i++){
       if(p[i]==0){
         p1=i;
         for(ll j=(i-1);j>=0;j--){
           if(p[j]!=0){
             p2=j;
           }
           else{
            break;
           }
         }
         //cout<<p2<<"@$@$"<<p1<<endl;
         stack<char> u;
         for(ll k=p2;k<=p1;k++){
           if(u.size()==0){
             u.push(s[k]);
           }
           else if(s[k]=='('){
             u.push(s[k]);
           }
           else{
            if(u.top()=='('){
              u.pop();
            }
            else{
             u.push(s[k]);
            }
           }
         }
           ans+=u.size();
       }
     }
     cout<<ans<<endl;
    }
    //printclock;
    return 0;
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//using namespace __gnu_pbds;
#define fastio() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb  push_back
#define show(x) cout<<(#x)<<" : "<<x<<endl;
#define ll  long long
#define ld  long double
#define fill(a,val) memset(a,val,sizeof(a))
#define mp  make_pair
#define ff  first
#define ss  second
#define pii pair<ll,ll>
#define sq(x) ((x)*(x))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define endl "\n"
#define int long long
#define in(a) cin>>a;
#define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n";
const ll MOD     = 1000*1000*1000+7;
const ll INF     = 1ll*1000*1000*1000*1000*1000*1000 + 7;
const ll MOD2    = 998244353;
const ll N       = 1000 * 100 + 10;
const ll N2      = 70;
const ld PI  = 3.141592653589793;
//template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
ll gcd(ll a, ll b){if(!b)return a;return gcd(b, a % b);}
ll power(ll x,ll y,ll p = LLONG_MAX ){ll res=1;x%=p;while(y>0){if(y&1)res=(res*x)%p;y=y>>1;x=(x*x)%p;}return res;}
ll lcm(ll a , ll b){return (a*b)/gcd(a,b);}
void solve(){
  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
  #endif
}
signed main()
{
    fastio();
    //cout<<fixed<<setprecision(20);
    //CHECK for LONG LONG and LONG DOUBLE
    //*comment for all except cc/cf
    ll n;
    cin>>n;
    string s;
    cin>>s;
    stack<char> p,q;
    for(ll i=0;i<n;i++){
      if(q.size()==0){
        q.push(s[i]);
      }
      else if(s[i]==')'){
       if(q.top()=='('){
         //cout<<'@'<<endl;
         q.pop();
       }
       else{
        q.push(s[i]);
       }
      }
      else{
       q.push(s[i]);
      }
    }
    if(q.size()==0){
      cout<<0<<endl;
      return 0;
    }
     for(ll i=0;i<n;i++){
      if(p.size()==0){
        p.push(s[i]);
      }
      else if(s[i]=='('){
        p.push(s[i]);
      }
      else{
       if(p.top()=='('){
         p.pop();
         p.push('a');
       }
       else{
        p.push(s[i]);
       }
      }
     }
     ll ans=0;
     ll co=0,cc=0,fl=1;
     while(p.size()>0){
      if(p.top()=='a'){
        if(co!=cc){
          fl=0;
          break;
        }
        ans+=(co+cc);
        co=0,cc=0;
        p.pop();
      }
      else{
       if(p.top()=='('){
         co++;
       }
       else{
         cc++;
       }
       p.pop();
      }
     }
     if(co!=cc){
       fl=0;
     }
     else{
      ans+=(co+cc);
     }
     if(fl==0){
       cout<<-1<<endl;
     }
     else{
      cout<<ans<<endl;
     }
    //printclock;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define mx 1000005

int ar[mx];
char ch[mx];

int n,m;

void solve(int ii)
{
    scanf("%d",&n);
    scanf("%s",ch);
    int aa=0,bb=0;
    for(int i=0; i<n; i++)
    {
        if(ch[i]=='(')
            aa++;
        else
            bb++;
    }
    int cnt1=0,cnt2=0;
    if(aa!=bb)
    {
        printf("-1\n");
        return;
    }

    for(int i=0; i<n; i++)
    {
        if(ch[i]=='(')
        {
            cnt1++;

        }

        else
        {
            cnt1--;

        }

        if(cnt1<0)
        {
            for(int j=i+1;j<n;j++)
            {
                if(ch[j]=='(')cnt1++;
                else cnt1--;
                if(cnt1==0)
                {
                    cnt2+=j-i+1;
                    i=j;
                    break;
                }
            }
        }
    }

    printf("%d\n",cnt2);
}
int main()
{
    int t=1;
    for(int i=1; i<=t; i++)
        solve(i);

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define mx 1000005

int ar[mx];
char ch[mx];

int n,m;

void solve(int ii)
{
     scanf("%d",&n);
     scanf("%s",ch);
     int cnt1=0,cnt2=0;
     if(n%2==1)
     {
         printf("-1\n");
         return;
     }
     int pos=0;
     for(int i=0;i<n;i++)
     {
         if(ch[i]=='(')cnt1++;
         else cnt1--;
        // if(cnt1==0)pos=i;

         if(cnt1<0)cnt2+=2,cnt1+=1;

     }

     printf("%d\n",cnt2+cnt1);
}
int main()
{
    int t=1;
    for(int i=1;i<=t;i++)solve(i);

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define mx 1000005

int ar[mx];
char ch[mx];

int n,m;

void solve(int ii)
{
     scanf("%d",&n);
     scanf("%s",ch);
     int cnt1=0,cnt2=0;
     if(n%2==1)
     {
         printf("-1\n");
         return;
     }
     int pos=0;
     bool f=true;
     for(int i=0;i<n;i++)
     {
         if(ch[i]=='(')
         {
             //cnt1++;
             if(f==false)
             {
                 int val=i-pos;
                 if(val%2==1)
                 {
                     cnt2+=val-1-2;
                     cnt1=1;
                     pos=i-1;

                 }
                 else
                 {
                    cnt2+=val-2;
                    cnt1=0;
                    pos=i;
                 }
                 f=true;

                 //cnt1=;
                 //pos=i;
             }
             else cnt1++;
         }
         else {
                cnt1--;
         f=false;
         }

         if(cnt1<0)cnt2+=2,cnt1=0,i++,f=true;
         if(cnt1==0)
         {
             pos=i;
         }
       //cout<<i<<" "<<cnt1<<" "<<pos<<endl;
     }

     printf("%d\n",cnt2+cnt1);
}
int main()
{
    int t=1;
    for(int i=1;i<=t;i++)solve(i);

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define mx 1000005

int ar[mx];
char ch[mx];

int n,m;

void solve(int ii)
{
    scanf("%d",&n);
    scanf("%s",ch);
    int aa=0,bb=0;
    for(int i=0; i<n; i++)
    {
        if(ch[i]=='(')
            aa++;
        else
            bb++;
    }
    int cnt1=0,cnt2=n;
    if(aa!=bb)
    {
        printf("-1\n");
        return;
    }
    int tem=0;
    bool f=true;
    for(int i=0; i<n; i++)
    {
        if(ch[i]=='(')
        {
            if(f==false)
            {
                cnt2-=2;
                tem=1;
                cnt1=1;
                f=true;
            }
            else
            {
                cnt1++;
                tem++;
            }
        }

        else
        {
            cnt1--;
            f=false;
        }
        if(cnt1==0)
        {
            cnt2-=tem;
            tem=0;
            f=true;
        }

        if(cnt1<0)
           {
               cnt2-=tem;
               tem=0;
               f=true;
               cnt1=0;
           }
        //cout<<i<<" "<<cnt1<<" "<<pos<<endl;
    }

    printf("%d\n",cnt2);
}
int main()
{
    int t=1;
    for(int i=1; i<=t; i++)
        solve(i);

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define mx 1000005

int ar[mx];
char ch[mx];

int n,m;

void solve(int ii)
{
    scanf("%d",&n);
    scanf("%s",ch);
    int aa=0,bb=0;
    for(int i=0; i<n; i++)
    {
        if(ch[i]=='(')
            aa++;
        else
            bb++;
    }
    int cnt1=0,cnt2=0;
    if(aa!=bb)
    {
        printf("-1\n");
        return;
    }
    int tem=0,best=0,pos1=0,pos2=-1;

    for(int i=0; i<n; i++)
    {
        if(ch[i]=='(')
        {
            cnt1++;
            pos1=i;
        }

        else
        {
            cnt2++;
            if(pos2==-1)pos2=i;

        }
        //cout<<cnt1<<" "<<cnt2<<endl;
        if(cnt1==cnt2)
        {
            if(pos1>pos2)best+=cnt1+cnt2;
            pos2=-1;
            cnt1=0;
            cnt2=0;
        }
    }

    printf("%d\n",best);
}
int main()
{
    int t=1;
    for(int i=1; i<=t; i++)
        solve(i);

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define mx 100005

int ar[mx];
char ch[mx];

int n,m;

void solve(int ii)
{
     scanf("%d",&n);
     scanf("%s",ch);
     int cnt1=0,cnt2=0;
     if(n%2==1)
     {
         printf("-1\n");
         return;
     }
     int pos=0;
     for(int i=0;i<n;i++)
     {
         if(ch[i]=='(')cnt1++;
         else cnt1--;
        // if(cnt1==0)pos=i;

         if(cnt1<0)cnt2+=2,cnt1+=1;

     }

     printf("%d\n",cnt2+cnt1);
}
int main()
{
    int t=1;
    for(int i=1;i<=t;i++)solve(i);

    return 0;
}


#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<iostream>
#include <fstream>
#include<sstream>
#include<set>
#include<map>
#include<queue>
#include<bitset>
#include<vector>
#include<limits.h>
#include<assert.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define FORS(I, S) for (int I = 0; S[I]; ++I)
#define RS(X) scanf("%s", (X))
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define CASET int ___T; scanf("%d", &___T); for(int cs=1;cs<=___T;cs++)
#define MP make_pair
#define pb push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define F first
#define S second
using namespace std;
typedef long long int lli;
typedef unsigned long long ULL;
typedef long double LD;

int main(){
    int n;
    string s;
    cin >> n;
    cin >> s;
    int l = 0;
    int r = 0;
    int cnto = 0;
    int cntc = 0;
    bool wrong = false;
    REP(i, n){
        if(s[i] == '('){
            cnto++;
        }
        if(s[i] == ')'){
            cntc++;
        }
    }
    if(cnto != cntc){
        cout << -1 << endl;
        return 0;
    }
    int cnt = 0;
    int ans = 0;
    int t = 0;
    for(int i = 0; i < n; i++){
        if(s[i] == '('){
            cnt++;
        }
        else{
            cnt--;
        }
        if(cnt < 0){
            wrong = true;
        }
        if(cnt == 0){
            if(wrong){
                ans += (i - t + 1);
            }
            t = i + 1;
            wrong = false;
        }

    }
    cout << ans << endl;
}


#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<iostream>
#include <fstream>
#include<sstream>
#include<set>
#include<map>
#include<queue>
#include<bitset>
#include<vector>
#include<limits.h>
#include<assert.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define FORS(I, S) for (int I = 0; S[I]; ++I)
#define RS(X) scanf("%s", (X))
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define CASET int ___T; scanf("%d", &___T); for(int cs=1;cs<=___T;cs++)
#define MP make_pair
#define pb push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define F first
#define S second
using namespace std;
typedef long long int lli;
typedef unsigned long long ULL;
typedef long double LD;

int main(){
    int n;
    string s;
    cin >> n;
    cin >> s;
    int l = 0;
    int r = 0;
    int cnto = 0;
    int cntc = 0;
    REP(i, n){
        if(s[i] == '('){
            cnto++;
        }
        if(s[i] == ')'){
            cntc++;
        }
    }
    if(cnto != cntc){
        cout << -1 << endl;
        return 0;
    }
    int i = 0;
    int cnt1 = 0;
    if(s[0] == ')'){
        for(i = 0; i < n; i++){
            if(s[i] == '('){
                break;
            }
            else{
                cnt1++;
            }
        }
    }

    int cnt2 = 0;
    int j = 0;
    if(s[n-1] == '('){
        for(j = n - 1; j>=(cnt1*2); j--){
            if(s[j] == ')') {
                break;
            }
            else{
                cnt2++;
            }
        }
    }
    int yyy = cnt2;
    cout << cnt1*2 + cnt2*2 << endl;
}


#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<iostream>
#include <fstream>
#include<sstream>
#include<set>
#include<map>
#include<queue>
#include<bitset>
#include<vector>
#include<limits.h>
#include<assert.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define FORS(I, S) for (int I = 0; S[I]; ++I)
#define RS(X) scanf("%s", (X))
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define CASET int ___T; scanf("%d", &___T); for(int cs=1;cs<=___T;cs++)
#define MP make_pair
#define pb push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define F first
#define S second
using namespace std;
typedef long long int lli;
typedef unsigned long long ULL;
typedef long double LD;

int main(){
    int n;
    string s;
    cin >> n;
    cin >> s;
    int l = 0;
    int r = 0;
    int cnto = 0;
    int cntc = 0;
    REP(i, n){
        if(s[i] == '('){
            cnto++;
        }
        if(s[i] == ')'){
            cntc++;
        }
    }
    if(cnto != cntc){
        cout << -1 << endl;
        return 0;
    }
    int i = 0;
    int cnt1 = 1;
    if(s[0] == ')'){
        for(i = 1; i < n; i++){
            if(s[i] == '('){
                break;
            }
            else{
                cnt1++;
            }
        }
    }

    int cnt2 = 1;
    int j = 0;
    if(s[n-1] == '('){
        for(j = n - 1; j>=0; j--){
            if(s[j] == ')') {
                cnt2++;
            }
        }
    }
    int yyy = cnt2;
    cout << cnt1*2 + cnt2*2 << endl;
}


#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<iostream>
#include <fstream>
#include<sstream>
#include<set>
#include<map>
#include<queue>
#include<bitset>
#include<vector>
#include<limits.h>
#include<assert.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define FORS(I, S) for (int I = 0; S[I]; ++I)
#define RS(X) scanf("%s", (X))
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define CASET int ___T; scanf("%d", &___T); for(int cs=1;cs<=___T;cs++)
#define MP make_pair
#define pb push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define F first
#define S second
using namespace std;
typedef long long int lli;
typedef unsigned long long ULL;
typedef long double LD;

int main(){
    int n;
    string s;
    cin >> n;
    cin >> s;
    int l = 0;
    int r = 0;
    int cnto = 0;
    int cntc = 0;
    REP(i, n){
        if(s[i] == '('){
            cnto++;
        }
        if(s[i] == ')'){
            cntc++;
        }
    }
    if(cnto != cntc){
        cout << -1 << endl;
        return 0;
    }
    int i = 0;
    int cnt1 = 1;
    if(s[0] == ')'){
        for(i = 1; i < n; i++){
            if(s[i] == '('){
                break;
            }
            else{
                cnt1++;
            }
        }
    }

    int cnt2 = 1;
    int j = 0;
    if(s[n-1] == '('){
        for(j = n - 2; j>=0; j--){
            if(s[j] == ')') {
                break;
            }
            else{
                cnt2++;
            }
        }
    }
    int yyy = cnt2;
    cout << cnt1*2 + cnt2*2 << endl;
}


#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll mod=1e9+7;
const ll N = 2e5+10;

void Solve(){
            ll n=0,r=0;cin>>n;
            string s;cin>>s;
            for(char &c:s){
                if(c=='(') r++;
                else r--;
            }
            if(r!=0){
                cout<<-1<<"\n";
                return;
            }
            int Sum = 0;
            int Ans = 0;

            for(char &c : s) {
                if (c == '(')
                    Sum++;
                if (c == ')')
                    Sum--;
                if (Sum < 0)
                    Ans++;
                if (Sum == -1 && c == ')')
                    Ans++;
            }
            cout<<Ans<<"\n";

}

int main(){

        #ifdef debug
            freopen("input.txt", "r", stdin);
            freopen("output.txt", "w", stdout);

        #endif
            ios_base::sync_with_stdio(0);
            cin.tie(0);cout.tie(0);

            ll T=1;
            while(T--){
                Solve();
            }

        return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll mod=1e9+7;
const ll N = 2e5+10;

void solve(){
            ll n=0,r=0;cin>>n;
            string s;cin>>s;
            for(char &c:s){
                if(c=='(') r++;
                else r--;
            }
            if(r!=0){
                cout<<-1<<"\n";
                return;
            }
            int Sum = 0;
            int Ans = 0;

            for(char &c : s) {
                if (c == '(')
                    Sum++;
                if (c == ')')
                    Sum--;
                if (Sum < 0)
                    Ans++;
                if (Sum == -1 && c == ')')
                    Ans++;
            }
            cout<<Ans<<"\n";

}

int main(){

        #ifdef debug
            freopen("input.txt", "r", stdin);
            freopen("output.txt", "w", stdout);

        #endif
            ios_base::sync_with_stdio(0);
            cin.tie(0);cout.tie(0);

            ll T=1;
            while(T--){
                solve();
            }

        return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll mod=1e9+7;
const ll N = 2e5+10;

void solve(){
          ll n=0;cin>>n;
          string s;cin>>s;
          if(n&1){
              cout<<-1<<"\n";
              return;
          }
          ll r=0,l=0,ans=0,f=0,rs=0;
          for (int i = 0; i < n; i+=2) {
              if(s[i]=='('){
                  if(s[i+1]==')'){
                      f=1;
                      continue;
                  }
                  else{
                      r+=2;

                  }
              }

              if(s[i]==')'){
                  if(s[i+1]=='('){
                      ans+=2;
                      rs=1;
                  }
                  else{
                      l+=2;

                  }

              }
              //cout<<l<<" "<<r<<"\n";
              if(f==1){
                  if(l==r&&rs!=1){
                      l=0;r=0;f=0;
                  }
                  else{
                      ans+=2*(min(l,r));
                       l-=min(l,r);r-=min(l,r);f=0;

                  }
              }
          }
          cout<<ans<<"\n";

}

int main(){

        #ifdef debug
            freopen("input.txt", "r", stdin);
            freopen("output.txt", "w", stdout);

        #endif
            ios_base::sync_with_stdio(0);
            cin.tie(0);cout.tie(0);

            ll T=1;
            //cin>>T;
            while(T--){
                solve();
            }

        return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll mod=1e9+7;
const ll N = 2e5+10;

void solve(){
            ll n=0;cin>>n;
            string s;cin>>s;
            if(n&1){
                cout<<-1<<"\n";
                return;
            }
            int Sum = 0;
            int Ans = 0;

            for(char &c : s) {
                if (c == '(')
                    Sum++;
                if (c == ')')
                    Sum--;
                if (Sum < 0)
                    Ans++;
                if (Sum == -1 && c == ')')
                    Ans++;
            }
            cout<<Ans<<"\n";

}

int main(){

        #ifdef debug
            freopen("input.txt", "r", stdin);
            freopen("output.txt", "w", stdout);

        #endif
            ios_base::sync_with_stdio(0);
            cin.tie(0);cout.tie(0);

            ll T=1;
            while(T--){
                solve();
            }

        return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll mod=1e9+7;
const ll N = 2e5+10;

void solve(){
          ll n=0;cin>>n;
          string s;cin>>s;
          if(n&1){
              cout<<-1<<"\n";
              return;
          }
          ll r=0,l=0,ans=0,f=0,rs=0;
          for (int i = 0; i < n; i+=2) {
              if(s[i]=='('){
                  if(s[i+1]==')'){
                      f=1;
                      continue;
                  }
                  else{
                      r+=2;

                  }
              }

              if(s[i]==')'){
                  if(s[i+1]=='('){
                      ans+=2;
                      rs=1;
                  }
                  else{
                      l+=2;

                  }

              }
              //cout<<l<<" "<<r<<"\n";
              if(f==1){
                  if(l==r&&rs!=1){
                      l=0;r=0;f=0;
                  }
                  else{
                      ans+=2*(min(l,r));
                       l=0;r=0;f=0;

                  }
              }
          }
          cout<<ans<<"\n";

}

int main(){

        #ifdef debug
            freopen("input.txt", "r", stdin);
            freopen("output.txt", "w", stdout);

        #endif
            ios_base::sync_with_stdio(0);
            cin.tie(0);cout.tie(0);

            ll T=1;
            //cin>>T;
            while(T--){
                solve();
            }

        return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll mod=1e9+7;
const ll N = 2e5+10;

void solve(){
          ll n=0;cin>>n;
          string s;cin>>s;
          if(n&1){
              cout<<-1<<"\n";
              return;
          }
          ll r=0,l=0,ans=0,f=0,rs=0;
          for (int i = 0; i < n; i+=2) {
              if(s[i]=='('){
                  if(s[i+1]==')'){
                      f=1;
                      continue;
                  }
                  else{
                      r+=2;

                  }
              }

              if(s[i]==')'){
                  if(s[i+1]=='('){
                      ans+=2;
                      rs=1;
                  }
                  else{
                      l+=2;

                  }

              }
              //cout<<l<<" "<<r<<"\n";
              if(f==1){
                  if(l==r&&rs!=1){
                      l=0;r=0;f=0;
                  }
                  else{
                      ans+=2*(min(l,r));
                       l-=min(l,r);r-=min(l,r);f=0;rs=0;

                  }
              }
          }
          cout<<ans<<"\n";

}

int main(){

        #ifdef debug
            freopen("input.txt", "r", stdin);
            freopen("output.txt", "w", stdout);

        #endif
            ios_base::sync_with_stdio(0);
            cin.tie(0);cout.tie(0);

            ll T=1;
            //cin>>T;
            while(T--){
                solve();
            }

        return 0;
}


// #pragma comment(linker, "/stack:200000000")
// #pragma GCC optimize("O3")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <random>
#include <chrono>
#include <complex>
#include <algorithm>
#include <utility>
#include <functional>
#include <cmath>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using namespace std;

#define sqr(x) ((x)*(x))
#define mp make_pair
#define pb push_back
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define RE(i, n) FOR(i,1,n)
#define REP(i,n) FOR(i, 0, (int)(n)-1)
#define fst first
#define snd second

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef tuple<int,int,int> iii;

string to_string(string s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

void fastIO() {
    cin.sync_with_stdio(false);
    cin.tie(0);
}

int XMOV[4] = {0, 0, 1, -1};
int YMOV[4] = {1, -1, 0, 0};

//#############################
const int MAXN = 1000005;

int main() {
    fastIO();
    int n;
    cin >> n;
    string s;
    cin >> s;

    int open = 0, close = 0;
    vector<int> balance(n+1, 0);

    for (int i = 0; i < n; i++)
        open += s[i] == '(', close += s[i] == ')';

    if (open != close){
        cout << -1 << endl;
        return 0;
    }

    for (int i = 1; i <= n; i++) {
        balance[i] = balance[i-1] + (s[i-1] == ')'? -1 : 1);
    }

    int i = 1, j = 1;
    int ans = 0;
    while(i <= n) {
        while(balance[i] >= 0)
            i++;
        j = i;
        while(balance[j] < 0)
            j++;
        ans += j-i;
        i = j;
    }
    cout << ans << endl;
    return 0;
}


// #pragma comment(linker, "/stack:200000000")
// #pragma GCC optimize("O3")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <random>
#include <chrono>
#include <complex>
#include <algorithm>
#include <utility>
#include <functional>
#include <cmath>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using namespace std;

#define sqr(x) ((x)*(x))
#define mp make_pair
#define pb push_back
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define RE(i, n) FOR(i,1,n)
#define REP(i,n) FOR(i, 0, (int)(n)-1)
#define fst first
#define snd second

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef tuple<int,int,int> iii;

string to_string(string s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

void fastIO() {
    cin.sync_with_stdio(false);
    cin.tie(0);
}

int XMOV[4] = {0, 0, 1, -1};
int YMOV[4] = {1, -1, 0, 0};

//#############################
const int MAXN = 1000005;

int main() {
    fastIO();
    int n;
    cin >> n;
    string s;
    cin >> s;

    int open = 0, close = 0;
    vector<int> balance(n+1, 0);

    for (int i = 0; i < n; i++)
        open += s[i] == '(', close += s[i] == ')';

    if (open != close){
        cout << -1 << endl;
        return 0;
    }

    for (int i = 1; i <= n; i++) {
        balance[i] = balance[i-1] + (s[i-1] == ')'? -1 : 1);
    }

    int i = 1, j = 1;
    int ans = 0;
    // cout << to_string(balance) << endl;
    while(i < n) {
        while(i < n && balance[i] >= 0)
            i++;
        if(i >= n)
            break;
        j = i;
        while(j < n && balance[j] < 0)
            j++;
        ans += j-i+1;
        i = j;
    }
    cout << ans << endl;
    return 0;
}


// #pragma comment(linker, "/stack:200000000")
// #pragma GCC optimize("O3")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <random>
#include <chrono>
#include <complex>
#include <algorithm>
#include <utility>
#include <functional>
#include <cmath>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using namespace std;

#define sqr(x) ((x)*(x))
#define mp make_pair
#define pb push_back
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define RE(i, n) FOR(i,1,n)
#define REP(i,n) FOR(i, 0, (int)(n)-1)
#define fst first
#define snd second

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef tuple<int,int,int> iii;

string to_string(string s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

void fastIO() {
    cin.sync_with_stdio(false);
    cin.tie(0);
}

int XMOV[4] = {0, 0, 1, -1};
int YMOV[4] = {1, -1, 0, 0};

//#############################
const int MAXN = 1000005;

int main() {
    fastIO();
    int n;
    cin >> n;
    string s;
    cin >> s;

    int open = 0, close = 0;
    vector<int> balance(n+1, 0);

    for (int i = 0; i < n; i++)
        open += s[i] == '(', close += s[i] == ')';

    if (open != close){
        cout << -1 << endl;
        return 0;
    }

    for (int i = 1; i <= n; i++) {
        balance[i] = balance[i-1] + (s[i-1] == ')'? -1 : 1);
    }

    int i = 1, j = 1;
    int ans = 0;
    cout << to_string(balance) << endl;
    while(i < n) {
        while(i < n && balance[i] >= 0)
            i++;
        if(i >= n)
            break;
        j = i;
        while(j < n && balance[j] < 0)
            j++;
        ans += j-i+1;
        i = j;
    }
    cout << ans << endl;
    return 0;
}


// #pragma comment(linker, "/stack:200000000")
// #pragma GCC optimize("O3")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <random>
#include <chrono>
#include <complex>
#include <algorithm>
#include <utility>
#include <functional>
#include <cmath>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using namespace std;

#define sqr(x) ((x)*(x))
#define mp make_pair
#define pb push_back
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define RE(i, n) FOR(i,1,n)
#define REP(i,n) FOR(i, 0, (int)(n)-1)
#define fst first
#define snd second

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef tuple<int,int,int> iii;

string to_string(string s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

void fastIO() {
    cin.sync_with_stdio(false);
    cin.tie(0);
}

int XMOV[4] = {0, 0, 1, -1};
int YMOV[4] = {1, -1, 0, 0};

//#############################
const int MAXN = 1000005;

int main() {
    fastIO();
    int n;
    cin >> n;
    string s;
    cin >> s;

    int open = 0, close = 0;
    vector<int> balance(n+1, 0);

    for (int i = 0; i < n; i++)
        open += s[i] == '(', close += s[i] == ')';

    if (open != close){
        cout << -1 << endl;
        return 0;
    }

    for (int i = 1; i <= n; i++) {
        balance[i] = balance[i-1] + (s[i-1] == ')'? -1 : 1);
    }

    int i = 1, j = 1;
    int ans = 0;
    // cout << to_string(balance) << endl;
    while(i < n) {
        while(i <= n && balance[i] >= 0)
            i++;
        j = i;
        while(j <= n && balance[j] < 0)
            j++;
        ans += j-i+1;
        i = j;
    }
    cout << ans << endl;
    return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define pii pair<int,int>
#define mod 1000000007
#define eps 0.000000001
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define sz(x) ((int)x.size())
#define ln(x) ((int)x.length())
#define mp make_pair
#define pb push_back
#define ff first
#define ss second
#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const double PI = acos(-1.0);
using namespace std;
int sum(int l, int r, vector<int> &arr)
{
    if(l < 0 || r < 0)
        return 0;
    int ans = arr[r];
    if(l)
        ans -= arr[l - 1];
    return ans;
}
int main()
{
    FASTIO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int bal[n];
    bal[0] = (s[0] == '('?1:-1);
    for(int i=1;i<n;i++)
    {
    	bal[i] = bal[i-1] + (s[i] == '(' ? 1 : -1);
    }
    // for(int i=0;i<n;i++)
    // 	cout<<bal[i]<<" ";
    if(bal[n-1])
    {
    	cout<<-1;
    	return 0;
    }
    int start=0, end=0, c=0;
    for(int i=1;i<n;i++)
    {
    	if((bal[i-1] <0 && bal[i]<=0) || (bal[i-1] <=0 && bal[i]<0)){
    		start = i-1;
    		break;
    	}
    }

    for(int i=1;i<n;i++)
    {
    	if((bal[i-1] <0 && bal[i]<=0) || (bal[i-1] <=0 && bal[i]<0)){
    		end = i;
    		c++;
    	}
    }
    // cout<<end-start+1;
    cout<<c+1;
    return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define pii pair<int,int>
#define mod 1000000007
#define eps 0.000000001
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define sz(x) ((int)x.size())
#define ln(x) ((int)x.length())
#define mp make_pair
#define pb push_back
#define ff first
#define ss second
#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const double PI = acos(-1.0);
using namespace std;
int sum(int l, int r, vector<int> &arr)
{
    if(l < 0 || r < 0)
        return 0;
    int ans = arr[r];
    if(l)
        ans -= arr[l - 1];
    return ans;
}
int main()
{
    FASTIO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int l = 0, r = 0;
    for(char x : s)
    {
        if(x == '(')
            l++;
        else
            r++;
    }
    if(l != r)
    {
        cout << -1;
        return 0;
    }
    int ans = -1;
    int lo = 0, hi = n;
    while(lo <= hi)
    {
        int mid = (lo + hi) / 2;
        // cout << "lo: " << lo << " hi: " << hi << endl;
        // cout << "mid: " << mid << endl;
        bool found = false;
        for(int i = 0; i < n && i + mid < n; i++)
        {
            // int a = sum(0, i-1, ob);
            // int b = sum(0, i-1, cb);
            // int c = sum(i+mid, n-1, ob);
            // int d = sum(i+mid, n-1, cb);
            stack<char> st;
            int e = 0, f = 0;
            for(int j = 0; j < i; j++)
            {
                if(s[j] == '(')
                    st.push(s[j]), e++;
                else
                {
                    if(st.empty())
                        e--;
                    else
                        st.pop();
                }
            }
            // while(!st.empty())
            //     e++, st.pop();
            // cout << e << " ";
            for(int j = i + mid; j < n; j++)
            {
                if(s[j] == '(')
                    st.push(s[i]), f++;
                else
                {
                    if(st.empty())
                        f--;
                    else
                        st.pop();
                }
            }
            // while(!st.empty())
            //     f++, st.pop();
            // cout << f << endl;
            if(e + f == 0 && e >= 0)
            {
                // cout << i << " " << mid << endl;
                // ans = mid, hi = mid - 1;
                // break;
                // ans = mid;
                found = true;
            }
            // else
            //     lo = mid + 1;
            // cout<<"new\n";
        }
        if(found)
            ans = mid, hi = mid - 1;
        else
            lo = mid + 1;
        // cout<<"lo: "<<lo<<" hi: "<<hi<<endl;
    }
    if(ans == -1)
    {
        stack<char> st;
        int diff = 0;
        for(int j = 0; j < n; j++)
        {
            if(s[j] == '(')
                st.push(s[j]), diff++;
            else
            {
                if(st.empty())
                    diff--;
                else
                    st.pop();
            }
        }
        if(diff == 0)
            cout << n;
        else
            cout << ans;
    }
    else
        cout << ans;
    return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define pii pair<int,int>
#define mod 1000000007
#define eps 0.000000001
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define sz(x) ((int)x.size())
#define ln(x) ((int)x.length())
#define mp make_pair
#define pb push_back
#define ff first
#define ss second
#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const double PI = acos(-1.0);
using namespace std;
int sum(int l, int r, vector<int> &arr)
{
    if(l < 0 || r < 0)
        return 0;
    int ans = arr[r];
    if(l)
        ans -= arr[l - 1];
    return ans;
}
int main()
{
    FASTIO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int bal[n];
    bal[0] = (s[0] == '(' ? 1 : -1);
    for(int i = 1; i < n; i++)
    {
        bal[i] = bal[i - 1] + (s[i] == '(' ? 1 : -1);
    }
    // for(int i=0;i<n;i++)
    // 	cout<<bal[i]<<" ";
    if(bal[n - 1])
    {
        cout << -1;
        return 0;
    }
    int start = 0, end = 0, c = 0;
    for(int i = 1; i < n; i++)
    {
        if((bal[i - 1] < 0 && bal[i] <= 0) || (bal[i - 1] <= 0 && bal[i] < 0))
        {
            start = i - 1;
            break;
        }
    }

    for(int i = 1; i < n; i++)
    {
        if((bal[i - 1] < 0 && bal[i] <= 0) || (bal[i - 1] <= 0 && bal[i] < 0))
        {
            end = i;
            c++;
        }
    }
    // cout<<end-start+1;
    if(s[0] == '(')
        cout << c;
    else
        cout << c + 1;
    return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define pii pair<int,int>
#define mod 1000000007
#define eps 0.000000001
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define sz(x) ((int)x.size())
#define ln(x) ((int)x.length())
#define mp make_pair
#define pb push_back
#define ff first
#define ss second
#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const double PI = acos(-1.0);
using namespace std;
int sum(int l, int r, vector<int> &arr)
{
    if(l < 0 || r < 0)
        return 0;
    int ans = arr[r];
    if(l)
        ans -= arr[l - 1];
    return ans;
}
int main()
{
    FASTIO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int l = 0, r = 0;
    for(char x : s)
    {
        if(x == '(')
            l++;
        else
            r++;
    }
    if(l != r)
    {
        cout << -1;
        return 0;
    }
    int ans = -1;
    int lo = 0, hi = n;
    vector<int> ob(n, 0), cb(n, 0);
    if(s[0] == '(')
        ob[0]++;
    else
        cb[0]++;

    for(int i = 1; i < n; i++)
    {
        ob[i] = ob[i - 1];
        cb[i] = cb[i - 1];
        if(s[i] == '(')
            ob[i]++;
        else
            cb[i]++;
    }
    while(lo <= hi)
    {
        int mid = (lo + hi) / 2;
        // cout << "mid: " << mid << endl;

        for(int i = 0; i < n && i + mid < n; i++)
        {
            // int a = sum(0, i-1, ob);
            // int b = sum(0, i-1, cb);
            // int c = sum(i+mid, n-1, ob);
            // int d = sum(i+mid, n-1, cb);
            stack<char> st;
            int e = 0, f = 0;
            for(int j = 0; j < i; j++)
            {
                if(s[j] == '(')
                    st.push(s[j]), e++;
                else
                {
                    if(st.empty())
                        e--;
                    else
                        st.pop();
                }
            }
            // while(!st.empty())
            //     e++, st.pop();
            // cout << e << " ";
            for(int j = i + mid; j < n; j++)
            {
                if(s[j] == '(')
                    st.push(s[i]),f++;
                else
                {
                    if(st.empty())
                        f--;
                    else
                        st.pop();
                }
            }
            // while(!st.empty())
            //     f++, st.pop();
            // cout << f << endl;
            if(e+f == 0 && e>=0)
            {
                // cout << i << " " << mid << endl;
                ans = mid, hi = mid - 1;
                // break;
            }
            else
                lo = mid + 1;
        }
    }
    cout << ans;
    return 0;
}


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string str)
{

    stack < char > st ;

    for(int i = l-1 ; i <= r-1 ; i++)
    {

        if(str[i]=='(')
        {
            st.push(str[i]);
            continue;
        }

        if(str[i]==')')
        {

            if(!st.empty())
            {
                if (st.top() == '(')
                {
                    st.pop();
                    continue;
                }
                else break;
            }
        }

    }

    if(st.empty())
        return true;
    else
        return false;

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')suja++;
        if(ss[i]==')')ulta++;

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {
            if( !isBalanced(cnt, i+1, ss) )
            {
                vec.push_back( make_pair( cnt, i+1 ) );
            }

            cnt = i+1;
            cnt++;
        }

    }

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int ans = 0 ;
    for(auto it:vec)
    {
//            cout << it.first <<" "<<it.second<<endl;
        ans = ans + it.second -  it.first + 1;

    }

    cout << ans <<endl;

    return 0;
}


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string str)
{

    stack < char > st ;

    for(int i = l-1 ; i <= r-1 ; i++)
    {

        if( !st.empty() and str[i] == ')' and st.top()=='(' )
        {
            st.pop();
        }
        else
        {
            st.push(str[i]);
        }
    }

    if(st.empty())
        return true;
    else
        return false;

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

    suja = count(ss.begin(), ss.end(),'(');
    ulta = count(ss.begin(),ss.end(),')');

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {
            vec.push_back( make_pair( cnt, i+1 ) );
            cnt = i+1;
            cnt++;
        }

    }

    int ans = 0 ;
    for(auto it:vec)
    {
        if(  isBalanced( it.first, it.second, ss) )
        {
//            cout << it.first <<" "<<it.second<<endl;
//            cout << "balanced" <<endl;

            ans+=0;

        }
        else
        {
            ans = ans + it.second -  it.first + 1;

//            cout << it.first <<" "<<it.second<<endl;
//            cout << "Not balanced" <<endl;

        }
    }

    cout << ans <<endl;
    // cout << it.first <<" "<<it.second<<endl;

    return 0;
}


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string s)
{

 bool f=0;
    stack<char> ok;
    for(int j=l-1 ;j<=r-1; j++)
    {
        if (s[j] == '(')
        {
            ok.push(s[j]);
            f = 1;
            continue;
        }
        if (!ok.empty())
        {
            if (s[j] == ')')
            {
                if (ok.top() == '(')
                {
                    ok.pop();
                    continue;
                }
                else break;
            }
        }
        else
        {
            break;
        }
    }
    if ((ok.empty()) && (f == 1))
    {
       return true;
    }
    else
    {
       return false;
    }

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

    suja = count(ss.begin(), ss.end(),'(');
    ulta = count(ss.begin(),ss.end(),')');

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int ans = 0 ;

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {

            if(!isBalanced(cnt,i+1,ss))
                  ans = ans + (i+1+1 - cnt);
               //vec.push_back( make_pair( cnt, i+1 ) );
            cnt = i+1;
            cnt++;
        }

    }

    cout << ans <<endl;
    // cout << it.first <<" "<<it.second<<endl;

    return 0;
}


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string str)
{

    stack < char > st ;

    int flag = 0 ;
    for(int i = l-1 ; i <= r-1 ; i++)
    {

        if(str[i]=='(')
        {
            flag = 1;
            st.push(str[i]);
            continue;
        }

        if(str[i]==')')
        {

            if(!st.empty())
            {
                if (st.top() == '(')
                {
                    st.pop();
                    continue;
                }
                else break;
            }
            else break;
        }

    }

    if(st.empty()and flag==1)
        return true;
    else
        return false;

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')suja++;
        if(ss[i]==')')ulta++;

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {
            if( !isBalanced(cnt, i+1, ss) )
            {
                vec.push_back( make_pair( cnt, i+1 ) );
            }

            cnt = i+1;
            cnt++;
        }

    }

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int ans = 0 ;
    for(auto it:vec)
    {
//            cout << it.first <<" "<<it.second<<endl;
        ans = ans + it.second -  it.first + 1;

    }

    cout << ans <<endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

int main(){

int n;
cin>>n;
string s;
cin>>s;

int dains = 0;
vector<pair<int,int>>stodain;
int l = 0,r = 0, bam=0, dain=0;
for(int i=0; i<s.size(); i++)
{
    if(s[i]=='(')
    {
        bam++;
    }
    else dain++;
    if(bam==dain)
    {
        stodain.push_back({l,r});
        l = r+1;
        bam=0;
        dain=0;
    }
    r++;
}
if(bam!=dain)
{
    cout<<-1<<endl;
    return 0;
}
for(int i=0; i<stodain.size(); i++)
{
    bool f=0;
    stack<char> ok;
    for(int j=stodain[i].first; j<=stodain[i].second; j++)
    {
        if (s[j] == '(')
        {
            ok.push(s[j]);
            f = 1;
            continue;
        }
        if (!ok.empty())
        {
            if (s[j] == ')')
            {
                if (ok.top() == '(')
                {
                    ok.pop();
                    continue;
                }
                else break;
            }
        }
        else
        {
            break;
        }
    }
    if ((ok.empty()) && (f == 1))
    {
        dains+=0;
    }
    else
    {
        dains+=((stodain[i].second-stodain[i].first)+1);
    }
}
cout<<dains<<endl;

return 0;
}


int n;
cin>>n;
string s;
cin>>s;

ll dains = 0;
vector<pair<int,int>>stodain;
int l = 0,r = 0, bam=0, dain=0;
for(int i=0; i<s.size(); i++)
{
    if(s[i]=='(')
    {
        bam++;
    }
    else dain++;
    if(bam==dain)
    {
        stodain.push_back({l,r});
        l = r+1;
        bam=0;
        dain=0;
    }
    r++;
}
if(bam!=dain)
{
    cout<<-1<<endl;
    return 0;
}
for(int i=0; i<stodain.size(); i++)
{
    bool f=0;
    stack<char> ok;
    for(int j=stodain[i].first; j<=stodain[i].second; j++)
    {
        if (s[j] == '(')
        {
            ok.push(s[j]);
            f = 1;
            continue;
        }
        if (!ok.empty())
        {
            if (s[j] == ')')
            {
                if (ok.top() == '(')
                {
                    ok.pop();
                    continue;
                }
                else break;
            }
        }
        else
        {
            break;
        }
    }
    if ((ok.empty()) && (f == 1))
    {
        dains+=0;
    }
    else
    {
        dains+=((stodain[i].second-stodain[i].first)+1);
    }
}
cout<<dains<<endl


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string str)
{

    stack < char > st ;

    for(int i = l-1 ; i <= r-1 ; i++)
    {

        if( !st.empty() and str[i] == ')' and st.top()=='(' )
        {
            st.pop();
        }
        else
        {
            st.push(str[i]);
        }
    }

    if(st.empty())
        return true;
    else
        return false;

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

//    suja = count(ss.begin(), ss.end(),'(');
//    ulta = count(ss.begin(),ss.end(),')');

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')suja++;
        if(ss[i]==')')ulta++;

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {

            if( !isBalanced(cnt, i+1, ss) )
            {
                vec.push_back( make_pair( cnt, i+1 ) );
            }

            cnt = i+1;
            cnt++;
        }

    }

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int ans = 0 ;
    for(auto it:vec)
    {

//            cout << it.first <<" "<<it.second<<endl;
        ans = ans + it.second -  it.first + 1;

    }

    cout << ans <<endl;

    return 0;
}


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string s)
{

 bool f=0;
    stack<char> ok;
    for(int j=l-1 ;j<=r-1; j++)
    {
        if (s[j] == '(')
        {
            ok.push(s[j]);
            f = 1;
            continue;
        }
        if (!ok.empty())
        {
            if (s[j] == ')')
            {
                if (ok.top() == '(')
                {
                    ok.pop();
                    continue;
                }
                else break;
            }
        }
        else
        {
            break;
        }
    }
    if ((ok.empty()) && (f == 1))
    {
       return true;
    }
    else
    {
       return false;
    }

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

    suja = count(ss.begin(), ss.end(),'(');
    ulta = count(ss.begin(),ss.end(),')');

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {

            if(!isBalanced(cnt,i+1,ss))
               vec.push_back( make_pair( cnt, i+1 ) );
            cnt = i+1;
            cnt++;
        }

    }

    int ans = 0 ;
    for(auto it:vec)
    {

            ans = ans + it.second -  it.first + 1;

    }

    cout << ans <<endl;
    // cout << it.first <<" "<<it.second<<endl;

    return 0;
}


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string s)
{

 bool f=0;
    stack<char> ok;
    for(int j=l-1 ;j<=r-1; j++)
    {
        if (s[j] == '(')
        {
            ok.push(s[j]);
            f = 1;
            continue;
        }
        if (!ok.empty())
        {
            if (s[j] == ')')
            {
                if (ok.top() == '(')
                {
                    ok.pop();
                    continue;
                }
                else break;
            }
        }
        else
        {
            break;
        }
    }
    if ((ok.empty()) && (f == 1))
    {
       return true;
    }
    else
    {
       return false;
    }

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

    suja = count(ss.begin(), ss.end(),'(');
    ulta = count(ss.begin(),ss.end(),')');

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {
            vec.push_back( make_pair( cnt, i+1 ) );
            cnt = i+1;
            cnt++;
        }

    }

    int ans = 0 ;
    for(auto it:vec)
    {
        if(  isBalanced( it.first, it.second, ss) )
        {
//            cout << it.first <<" "<<it.second<<endl;
//            cout << "balanced" <<endl;

            ans+=0;

        }
        else
        {
            ans = ans + it.second -  it.first + 1;

//            cout << it.first <<" "<<it.second<<endl;
//            cout << "Not balanced" <<endl;

        }
    }

    cout << ans <<endl;
    // cout << it.first <<" "<<it.second<<endl;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

int main()
{

    int n;
    cin>>n;
    string s;
    cin>>s;

    int dains = 0;
    vector<pair<int,int>>stodain;
    int l = 0,r = 0, bam=0, dain=0;

    int sum = 0 ;

    for(int i=0; i<s.size(); i++)
    {
        if(s[i]=='(')
        {
           //bam++;
           sum++;
        }
        else //dain++;
            sum--;
        if(sum==0)
        {
            stodain.push_back({l,r});
            l = r+1;
            bam=0;
            dain=0;
        }
        r++;
    }
    if(bam!=dain)
    {
        cout<<-1<<endl;
        return 0;
    }
    for(int i=0; i<stodain.size(); i++)
    {
        bool f=0;
        stack<char> ok;
        for(int j=stodain[i].first; j<=stodain[i].second; j++)
        {
            if (s[j] == '(')
            {
                ok.push(s[j]);
                f = 1;
                continue;
            }
            if (!ok.empty())
            {
                if (s[j] == ')')
                {
                    if (ok.top() == '(')
                    {
                        ok.pop();
                        continue;
                    }
                    else break;
                }
            }
            else
            {
                break;
            }
        }
        if ((ok.empty()) && (f == 1))
        {
            dains+=0;
        }
        else
        {
            dains+=((stodain[i].second-stodain[i].first)+1);
        }
    }
    cout<<dains<<endl;

    return 0;
}


/*

Bismillah_hir_rahmanir_rahim

*/
#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define inf ( ll  )( 1e18 + 100 )
#define bug cout <<"--------------------------\n"

///int dx[] = {0, 0, -1, +1}, dy[] = {-1, +1, 0, 0}; //4 Direction Array

///int dx[] = {0, 0, -1, +1, -1, -1, +1, +1}, dy[] = {-1, +1, 0, 0, -1, +1, -1, +1}; //8 Direction Array

///int dx[] = {-2, -2, -1, -1, +1, +1, +2, +2}, dy[] = {-1, +1, -2, +2, -2, +2, -1, +1}; //Knight Moves

///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction

vector < pair < int, int > > vec;

bool isBalanced(int l, int r, string str)
{

    stack < char > st ;

    for(int i = l-1 ; i <= r-1 ; i++)
    {

        if( !st.empty() and str[i] == ')' and st.top()=='(' )
        {
            st.pop();
        }
        else
        {
            st.push(str[i]);
        }
    }

    if(st.empty())
        return true;
    else
        return false;

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n ;

    cin >> n ;

    string ss ;

    cin >> ss ;

    int suja = 0, ulta = 0 ;

    suja = count(ss.begin(), ss.end(),'(');
    ulta = count(ss.begin(),ss.end(),')');

    if( suja != ulta )
    {
        cout << -1 <<endl;
        return 0;
    }

    int sum = 0 ;

    int cnt = 1 ;

    for(int i = 0 ; i < ss.length() ; i++)
    {

        if(ss[i]=='(')
            sum++;
        else if(ss[i]==')')sum--;

        if(sum==0)
        {
            vec.push_back( make_pair( cnt, i+1 ) );
            cnt = i+1;
            cnt++;
        }

    }

    int ans = 0 ;
    for(auto it:vec)
    {
        if(  !isBalanced( it.first, it.second, ss) )
        {
//            cout << it.first <<" "<<it.second<<endl;
            ans = ans + it.second -  it.first + 1;

        }

    }

    cout << ans <<endl;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main() {
	ll n;
	cin>>n;
	string s;
	cin>>s;
	if(n%2)
	{
	cout<<-1<<endl;return 0;}
	ll o=0,c=0,ao=0,ans=0,ac=0,index=-1,flag=0;;
	for(ll i=0;i<s.length();i++)
	{
		if(s[i]==')')
		{

	c++;
	if(o<c)
	flag=1;
		}
        else
        {
        	o++;

        }
        if(c==o&&flag==1)
        {
        //	cout<<i-index<<endl;
        flag=0;
        ans+=i-index;index=i;o=0,c=0;ao=0;ac=0;}
        else if(o==c&&flag==0){
        index=i;o=0,c=0,ac=0,ao=0;}

	}
	if(o!=c)
	{
		cout<<-1<<endl;
		return 0;
	}
	if(flag==1)
	ans+=n-1-index;

	cout<<ans<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main() {
	ll n;
	cin>>n;
	string s;
	cin>>s;
	if(n%2)
	{
	cout<<-1<<endl;return 0;}
	ll o=0,c=0,ao=0,ans=0,ac=0,index=-1,flag=0;;
	for(ll i=0;i<s.length();i++)
	{
		if(s[i]==')')
		{

	c++;
	if(o<c)
	flag=1;
		}
        else
        {
        	o++;

        }
        if(c==o&&flag==1)
        {
        //	cout<<i-index<<endl;flag=0;
        ans+=i-index;index=i;o=0,c=0;ao=0;ac=0;}
        else if(o==c&&flag==0){
        index=i;o=0,c=0,ac=0,ao=0;}

	}
	if(ao!=ac)
	{
		cout<<-1<<endl;
		return 0;
	}
	ans+=n-1-index;
	cout<<ans<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main() {
	ll n;
	cin>>n;
	string s;
	cin>>s;
	if(n%2)
	{
	cout<<-1<<endl;return 0;}
	ll o=0,c=0,ao=0,ans=0,ac=0,index=-1;
	for(ll i=0;i<s.length();i++)
	{
		if(s[i]==')')
		{
	ac++;
		}
        else
        {
        	ao++;;
        }
        if(ac==ao)
        {
        ans+=i-index;index=i;}

	}
	if(ao!=ac)
	{
		cout<<-1<<endl;
		return 0;
	}
	ans+=(o/2);
	cout<<ans<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main() {
	ll n;
	cin>>n;
	string s;
	cin>>s;
	if(n%2)
	{
	cout<<-1<<endl;return 0;}
	ll o=0,c=0,ao=0,ans=0,ac=0,index=-1,flag=0;;
	for(ll i=0;i<s.length();i++)
	{
		if(s[i]==')')
		{

	c++;
	if(o<c)
	flag=1;
		}
        else
        {
        	o++;

        }
        if(c==o&&flag==1)
        {
        //	cout<<i-index<<endl;flag=0;
        ans+=i-index;index=i;o=0,c=0;ao=0;ac=0;}
        else if(o==c&&flag==0){
        index=i;o=0,c=0,ac=0,ao=0;}

	}
	if(o!=c)
	{
		cout<<-1<<endl;
		return 0;
	}
	ans+=n-1-index;
	cout<<ans<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main() {
	ll n;
	cin>>n;
	string s;
	cin>>s;
	if(n%2)
	{
	cout<<-1<<endl;return 0;}
	ll o=0,c=0,ao=0,ans=0,ac=0,index=-1;
	for(ll i=0;i<s.length();i++)
	{
		if(s[i]==')')
		{
	ac++;
	if(o==0)
	c++;
		}
        else
        {
        	o++;
        	ao++;;
        }
        if(c==o)
        {
        //	cout<<i-index<<endl;
        ans+=i-index;index=i;o=0,c=0;}
        if(ao==ac){
        index=i;o=0,c=0,ac=0,ao=0;}

	}
	if(ao!=ac)
	{
		cout<<-1<<endl;
		return 0;
	}
	ans+=n-1-index;
	cout<<ans<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define M  1000000007

#define deb(x) cout << #x << " " << x << endl;
#define fo(i,n) for(int i=0;i<n;i++)
#define Fo(i,k,n) for(int i=k;i<=n;i++)
#define nl endl

// template<typename... T>
// void read(T&... args){
// 	((cin >> args) , ...);
// }

// void write(T... args){
// 	((cout << args << " "),...);
// }

int lcm(int a, int b){
	int x = (a*b)%M;
	return x/__gcd(a,b);
}

int ceil(int a, int b){
	if(a%b!=0) return a/b+1;
	return a/b;
}

bool f(string s){
	ll n = s.size();
	fo(i,n){
		if(s[i]!='1' && s[i]!='4')
			return false;
		if(s[0]!='1') return false;
		if(s.find("444")!=s.npos) return  false;
	}
	return true;
}

int main(){
	ll t;
	t = 1;
	// cin >> t;
	while(t--){
		int n;
		string s;
		cin >> n >> s;
		int sum = 0;
		int ans = 0,prev = 0;
		for(char c:s){
			if(c=='(') sum++;
			if(c==')') sum--;
			if(sum<0 || prev < 0) ans++;
			prev = sum;
			// if(sum==-1 && c==')') ans++;
		}
		if(sum){
			cout << -1 << endl;
			return 0;
		}
		cout << ans << endl;
	}

}


#include <bits/stdc++.h>

using namespace std;
using lint=long long;

int N,A[1000000],B[1000000],Ans;
string S;

int main(){

	cin>>N;
	cin>>S;
	for(int i=0;i<N;++i){
		if(i!=0){
			A[i]+=A[i-1];
			B[i]+=B[i-1];
		}
		if(S[i]=='(') A[i]++;
		else B[i]++;
	}
	if(A[N-1]!=B[N-1]){
		puts("-1");
		return 0;
	}
	for(int i=0;i<N;++i){
		for(int j=i;j<N;++j){
			if(A[j]==B[j]){
				if(S[i]==')') Ans+=j-i+1;
				i=j;
				break;
			}
		}
	}
	cout<<Ans<<'\n';
	return 0;
}