#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void read(T& x) {
  bool fu = 0;
  char c;
  for (c = getchar(); c <= 32; c = getchar())
    ;
  if (c == '-') fu = 1, c = getchar();
  for (x = 0; c > 32; c = getchar()) x = x * 10 + c - '0';
  if (fu) x = -x;
};
inline char getc() {
  char c;
  for (c = getchar(); c <= 32; c = getchar())
    ;
  return c;
}
const int N = 1000010;
int n, zui, i, j, k, l, p, g, a[N], c[N], q[N], ci[N], T[N];
bool v[N];
long long ans;
int find(int x, int y, int s) {
  int m;
  while (x < y) {
    m = (x + y) / 2;
    if (q[m] <= s)
      y = m;
    else
      x = m + 1;
  }
  return x;
}
long long solve() {
  int i, j, k, l, p;
  long long tot = 0;
  j = 0;
  for (i = 1; i <= g; i++) {
    for (; j > 0 && c[i] > q[j]; j--) tot++;
    if (c[i] < q[j])
      tot++;
    else
      tot += j - max(1, find(1, j, c[i]) - 1) + 1;
    ++j, q[j] = c[i];
  }
  return tot;
}
int ne(int i) { return i % n + 1; }
int la(int i) { return (i - 2 + n) % n + 1; }
int main() {
  read(n);
  for (i = 1; i <= n; i++) read(a[i]);
  p = 0;
  for (i = 1; i <= n; i++) p = max(p, a[i]);
  for (i = 1; i <= n; i++)
    if (a[i] == p) {
      g = 0;
      for (j = i % n + 1; a[j] < p; j = j % n + 1) c[++g] = a[j];
      ans += solve();
      zui++;
      k = -1;
      for (j = ne(i); a[j] != p; j = ne(j))
        if (a[j] >= k) {
          ans++;
          k = a[j];
          T[j] = i;
        }
      k = -1;
      for (j = la(i); a[j] != p; j = la(j))
        if (a[j] >= k) {
          ans += (T[j] != i);
          k = a[j];
          T[j] = i;
        }
    }
  ans += 1LL * zui * (zui - 1) / 2;
  cout << ans << endl;
  scanf("\n");
  return 0;
}
