#include <bits/stdc++.h>
using namespace std;
long long l[1200000], r[1200000], h[1200000];
long long n;
long long c[1200000];
int main() {
  scanf("%I64d", &n);
  for (long long i = 1; i <= n; i++) scanf("%I64d", &h[i]);
  long long maxn = 0, p;
  for (long long i = 1; i <= n; i++)
    if (h[i] > maxn) maxn = h[i], p = i;
  for (long long i = 1; i <= p - 1; i++) h[n + i] = h[i];
  for (long long i = p; i <= n + p - 1; i++) h[i - p + 1] = h[i];
  h[++n] = maxn;
  l[1] = 0;
  memset(c, 0, sizeof(c));
  for (long long i = 2; i <= n; i++) {
    l[i] = i - 1;
    while (h[l[i]] < h[i]) l[i] = l[l[i]];
    if (h[i] == h[l[i]]) {
      c[i] = c[l[i]] + 1;
      l[i] = l[l[i]];
    }
  }
  r[n] = n + 1;
  for (long long i = n - 1; i >= 1; i--) {
    r[i] = i + 1;
    while (h[r[i]] < h[i]) r[i] = r[r[i]];
    if (h[i] == h[r[i]]) {
      r[i] = r[r[i]];
    }
  }
  long long ans = 0;
  for (long long i = 2; i <= n - 1; i++) {
    ans += c[i] + 2;
    if (l[i] == 0) ans--;
    if (r[i] == n + 1) ans--;
    if (l[i] == 1 && r[i] == n) ans--;
  }
  printf("%I64d\n", ans);
  return 0;
}
