#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  vector<int> h;
  cin >> n;
  int maxh = -1, imax = -1;
  for (int i = 0; i < (int)(n); i++) {
    int a;
    cin >> a;
    h.push_back(a);
    if (maxh < a) {
      maxh = a;
      imax = i;
    }
  }
  long long int res = 0;
  deque<pair<int, int> > cola;
  int i = imax;
  for (int j = 0; j < (int)(n); j++) {
    int tmp = 0;
    while (!cola.empty() && cola.back().first < h[i]) {
      tmp += cola.back().second;
      cola.pop_back();
    }
    if (!cola.empty() && cola.back().first == h[i]) {
      tmp += cola.back().second;
      cola.back().second++;
    } else
      cola.push_back(make_pair(h[i], 1));
    if (!cola.empty() && cola.front().first > h[i]) tmp++;
    res += tmp;
    i++;
    if (i == n) i = 0;
  }
  pair<int, int> mm[n];
  mm[imax].first = mm[imax].second = 0;
  int i1 = imax + 1, i2 = imax - 1;
  for (int j = 0; j < (int)(n); j++) {
    if (i1 == n) i1 = 0;
    if (i2 == -1) i2 = n - 1;
    mm[i1].first = max(mm[(i1 - 1 + n) % n].first, h[i1]);
    mm[i2].second = max(mm[(i2 + 1 + n) % n].second, h[i2]);
    i1++;
    i2--;
  }
  for (int i = 0; i < (int)(n); i++) {
    if (i == imax) continue;
    if (h[i] != mm[i].first && h[i] == mm[i].second) res++;
  }
  cout << res << endl;
  return 0;
}
