#include <bits/stdc++.h>
using namespace std;
const long long maxn = 2 * 1e6 + 10;
long long a[maxn], b[maxn], q[maxn], sz[maxn], n;
inline long long read() {
  long long x = 0, f = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = (x << 1) + (x << 3) + c - '0';
    c = getchar();
  }
  return x * f;
}
long long b1, b2, n1;
signed main() {
  n = read();
  long long p = 0;
  for (long long i = 1; i <= n; i++) {
    a[i] = read();
    if (a[i] > a[p]) p = i;
    if (a[i] > b1)
      b2 = b1, b1 = a[i], n1 = 1;
    else if (a[i] == b1)
      n1++;
    else if (a[i] > b2)
      b2 = a[i];
  }
  for (long long i = 1; i <= n; i++) b[i] = a[(i + p - 1) % n + 1];
  long long l = 1, r = 0, ans = 0;
  for (long long i = 1; i <= n; i++) {
    while (l <= r && b[i] > b[q[r]]) r--, ans++;
    if (r >= l) {
      if (b[i] == b[q[r]])
        ans += min(r, sz[r] + 1);
      else
        ans++;
    }
    q[++r] = i;
    if (b[i] == b[q[r - 1]])
      sz[r] = sz[r - 1] + 1;
    else
      sz[r] = 1;
  }
  p = 0;
  for (long long i = 1; i < n; i++)
    if (b[i] >= b[p]) {
      p = i;
      if (n1 > 1 && b[p] == b1)
        ;
      else if (n1 == 1 && b[p] == b2)
        ;
      else
        ans++;
    }
  printf("%lld\n", ans);
  return 0;
}
