#include <bits/stdc++.h>
using namespace std;
const int N = 2000100;
int n, x[N], st[N], top, dr, nrel[N], nx[N];
long long rez;
int main() {
  int i;
  int elmax = 0, nrmax = 0, pmax;
  cin >> n;
  for (i = 1; i <= n; ++i) {
    scanf("%d", &x[i]);
    x[i + n] = x[i];
    if (x[i] > elmax) {
      elmax = x[i];
      pmax = i;
      nrmax = 0;
    }
    if (x[i] == elmax) ++nrmax;
  }
  i = pmax;
  for (int j = 1; j <= n; ++j) {
    nx[j] = x[i];
    ++i;
    if (i > n) i = 1;
  }
  for (i = 1; i <= n; ++i) x[i] = nx[i];
  x[n + 1] = elmax;
  if (nrmax > 1)
    rez -= nrmax;
  else {
    int nrmax2 = 0, elmax2 = 0;
    for (i = 1; i <= n; ++i)
      if (x[i] == elmax) break;
    for (++i; i <= 2 * n && x[i] != elmax; ++i) {
      if (x[i] > elmax2) {
        elmax2 = x[i];
        nrmax2 = 0;
      }
      if (x[i] == elmax2) ++nrmax2;
    }
    rez -= nrmax2 + 1;
  }
  for (i = n + 1; i; --i) {
    while (top && x[st[top]] < x[i]) {
      --top;
      ++rez;
    }
    if (top) {
      if (x[i] == x[st[top]]) {
        rez += nrel[top];
        if (top - nrel[top] > 0) rez++;
      } else
        ++rez;
    }
    st[++top] = i;
    nrel[top] = 1;
    if (top > 1 && x[st[top]] == x[st[top - 1]]) nrel[top] += nrel[top - 1];
  }
  cout << rez;
  return 0;
}
