#include <bits/stdc++.h>
using namespace std;
const int LEN = 200005;
char STR[LEN], *ST = STR, *ED = STR;
inline char gc() {
  if (ST == ED) {
    ED = (ST = STR) + fread(STR, 1, LEN, stdin);
    if (ST == ED) return EOF;
  }
  return *ST++;
}
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
const int N = 1000005;
int a[N], top;
int d[N], n;
int num[N];
int Mx, cnt;
long long ans;
int main() {
  n = read();
  for (int i = 1; i <= n; ++i) {
    a[i] = read();
    if (Mx < a[i]) {
      Mx = a[i];
      cnt = i;
    }
  }
  for (int i = cnt; i <= n; ++i) d[i - cnt] = a[i];
  for (int i = 1; i <= cnt; ++i) d[n - cnt + i] = a[i];
  top = 1;
  a[top] = d[0];
  num[top] = 1;
  for (int i = 1; i <= n; ++i) {
    while (top > 0 && a[top] < d[i]) {
      ans += num[top];
      --top;
    }
    if (top > 0 && a[top] == d[i]) {
      ans += num[top];
      num[top]++;
      if (top > 1) ++ans;
    } else {
      if (top > 0) ++ans;
      a[++top] = d[i];
      num[top] = 1;
    }
  }
  if (num[1] == 2) ans -= num[2];
  ans -= num[1] - 1;
  printf("%lld\n", ans);
  return 0;
}
