#include <bits/stdc++.h>
using namespace std;
inline void read(register int *n) {
  register char c;
  *n = 0;
  do {
    c = getchar();
  } while (c < '0' || c > '9');
  do {
    *n = c - '0' + *n * 10;
    c = getchar();
  } while (c >= '0' && c <= '9');
}
int bt(vector<int> V) {
  int tot = 0, n = ((int)(V).size());
  for (register int i = (0); i < (int)(n); ++i)
    for (register int j = (i + 1); j < (int)(n); ++j) {
      int pos = (i + 1) % n;
      bool ok = true;
      while (pos != j) {
        if (V[pos] > V[i] || V[pos] > V[j]) ok = false;
        pos = (pos + 1) % n;
      }
      bool ok2 = true;
      pos = (j + 1) % n;
      while (pos != i) {
        if (V[pos] > V[i] || V[pos] > V[j]) ok2 = false;
        pos = (pos + 1) % n;
      }
      if (ok || ok2) tot++;
    }
  return tot;
}
int main() {
  ios::sync_with_stdio(false);
  int n = 50;
  srand(time(NULL));
  cin >> n;
  vector<int> V(n);
  for (register int i = (0); i < (int)(n); ++i) cin >> V[i];
  long long tot = 0, mcnt = 0;
  int mx = *max_element((V).begin(), (V).end()), m2 = -1;
  for (register int i = (0); i < (int)(((int)(V).size())); ++i)
    mcnt += V[i] == mx;
  for (register int i = (0); i < (int)(((int)(V).size())); ++i)
    if (V[i] < mx) m2 = max(m2, V[i]);
  if (mcnt == 1)
    for (register int i = (0); i < (int)(((int)(V).size())); ++i)
      if (V[i] == m2) tot--;
  tot += mcnt * (mcnt - 1) / 2;
  deque<pair<int, int> > Q;
  for (register int i = (0); i < (int)(2 * n); ++i) {
    pair<int, int> cur(V[i % n], i);
    while (!Q.empty() && Q.back().second <= i - n) Q.pop_back();
    if (i >= n) {
      const int GO = 300;
      int pos = 0;
      while (pos + GO < ((int)(Q).size()) && Q[pos + GO].first < cur.first)
        pos += GO;
      while (pos < ((int)(Q).size()) && Q[pos].first < cur.first) pos++;
      while (cur.first != mx && pos + GO < ((int)(Q).size()) &&
             Q[pos + GO].first <= cur.first)
        pos += GO;
      while (cur.first != mx && pos < ((int)(Q).size()) &&
             Q[pos].first <= cur.first)
        pos++;
      if (pos < ((int)(Q).size()) && cur.first != mx) pos++;
      tot += pos;
    }
    while (!Q.empty() && Q.front().first < cur.first) Q.pop_front();
    Q.push_front(cur);
  }
  cout << tot << "\n";
  return 0;
}
