#include <bits/stdc++.h>
const int N = 1000005;
char c[11 * N];
int g[N], h[N], l[N], r[N], w[N];
int i, k, n, t;
long long s;
inline int fastscanf() {
  int t = 0;
  k++;
  while (!((c[k] > 47) && (c[k] < 58))) k++;
  while ((c[k] > 47) && (c[k] < 58)) t = t * 10 + c[k] - 48, k++;
  return t;
}
int main() {
  fread(c + 1, 1, 11 * N - 1, stdin);
  n = fastscanf();
  for (i = 1; i <= n; i++) g[i] = fastscanf();
  t = 1;
  for (i = 2; i <= n; i++)
    if (g[i] > g[t]) t = i;
  for (i = t; i <= n; i++) h[i - t + 1] = g[i];
  for (i = 1; i < t; i++) h[n - t + i + 1] = g[i];
  for (i = 2; i <= n; i++) {
    l[i] = i - 1;
    while ((l[i]) && (h[i] > h[l[i]])) l[i] = l[l[i]];
    if (h[i] == h[l[i]]) w[i] = w[l[i]] + 1, l[i] = l[l[i]];
  }
  for (i = n - 1; i > 0; i--) {
    r[i] = i + 1;
    while ((r[i]) && (h[i] >= h[r[i]])) r[i] = r[r[i]];
  }
  for (i = 1; i <= n; i++) {
    if (l[i]) s++;
    if ((r[i]) || ((l[i] != 1) && (h[i] != h[1]))) s++;
    s = s + w[i];
  }
  printf("%I64d", s);
  return 0;
}
