#include <bits/stdc++.h>
using namespace std;
using lint = long long;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  vector<int> h(n * 2);
  for (int i = 0; i < (int)(n); ++i) {
    cin >> h[i];
    h[i + n] = h[i];
  }
  int mx = *max_element(h.begin(), h.end());
  int cmx = 0;
  for (int i = 0; i < (int)(n); ++i) {
    if (h[i] == mx) {
      cmx++;
    }
  }
  lint ans = 0;
  deque<pair<int, int>> q;
  vector<int> bs(2 * n, -1);
  for (int i = 0; i < (int)(2 * n); ++i) {
    if (!q.empty() && q.back().second == i - n + 1) {
      q.pop_back();
    }
    if (i >= n && h[i] != mx) {
      int x = lower_bound(q.begin(), q.end(), make_pair(h[i], int(1e9))) -
              q.begin();
      if (x != q.size()) {
        bs[i] = bs[i - n] = q[x].second;
        x++;
      }
      ans += x;
    }
    while (!q.empty() && q.front().first < h[i]) {
      q.pop_front();
    }
    q.push_front({h[i], i});
  }
  ans += 1LL * cmx * (cmx - 1) / 2;
  for (int i = n; i < 2 * n; i++) {
    if (h[i] != mx) {
      continue;
    }
    int cc = 0;
    int j = i - 1;
    while (j >= 0 && h[j] != mx) {
      if (h[j] >= cc && bs[j] != i - n && bs[j] != i) {
        ans++;
      }
      cc = max(cc, h[j]);
      j--;
    }
  }
  cout << ans;
  return 0;
}
