#include <bits/stdc++.h>
using namespace std;
typedef struct {
  int h;
  int i;
} hill;
int n;
int m;
hill h[1000430];
long long total = 0;
set<int> neighbor;
vector<int> add;
map<int, int> d;
bool cmp(hill h1, hill h2) { return h1.h > h2.h; }
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &h[i].h);
    h[i].i = i;
  }
  sort(h, h + n, cmp);
  m = h[0].h;
  for (int i = 0; i < n; i++) {
    if (h[i].h == m) {
      total += i;
      neighbor.insert(h[i].i);
      continue;
    }
    if (h[i].h != h[i - 1].h) {
      for (int j = 0; j < add.size(); j++) {
        neighbor.insert(add[j]);
      }
      add.clear();
      d.clear();
    }
    set<int>::iterator it2 = neighbor.upper_bound(h[i].i);
    int b;
    int a;
    if (it2 == neighbor.end()) {
      it2 = neighbor.begin();
      b = *(it2);
    } else {
      b = *(it2);
    }
    if (it2 != neighbor.begin()) {
      a = *(--it2);
    } else {
      it2 = (neighbor.end());
      a = *(--it2);
    }
    total += 2 - (int)((a - b) % n == 0);
    add.push_back(h[i].i);
    total += d[b % n];
    if (d[b % n] > 0)
      d[b % n]++;
    else
      d[b % n] = 1;
  }
  printf("%I64d\n", total);
  fflush(stdin);
  getchar();
}
