#include <bits/stdc++.h>
using namespace std;
int N;
vector<bool> s;
int process() {
  int min = -1;
  int max = -1;
  int sum = 0;
  int ans = 0;
  for (int i = 0; i < s.size(); i++) {
    sum += s[i] ? 1 : -1;
    if (sum < 0) {
      int tSum = -1;
      min = i;
      while (tSum < 0) {
        i++;
        sum += s[i] ? 1 : -1;
        tSum += s[i] ? 1 : -1;
      }
      ans += (i - min + 1);
    }
  }
  return ans;
}
int main() {
  cin >> N;
  int sum = 0;
  int ans = 0;
  for (int i = 0; i < N; i++) {
    char c = cin.get();
    while (c != '(' && c != ')') {
      c = cin.get();
    }
    s.push_back((c == '('));
    sum += (c == '(') ? 1 : -1;
    if (sum == 0) {
      ans += process();
      s.clear();
    }
  }
  if (sum == 0) {
    cout << ans << endl;
  } else {
    cout << -1 << endl;
  }
  return 0;
}
