#include <bits/stdc++.h>
int h[1010000], d[1010000], a[1010000], f[1010000], t, n;
long long ans;
int bin(int x) {
  int ret = 1, l, r, m;
  for (l = 1, r = t; l <= r;) {
    m = (l + r) >> 1;
    if (a[m] <= x)
      r = m - 1;
    else
      ret = m, l = m + 1;
  }
  return ret;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%d", h + i);
    if (h[i] > h[t]) t = i;
  }
  for (int i = 0; i < n; ++i) d[i] = i + t < n ? h[i + t] : h[i + t - n];
  t = 0;
  for (int i = 0; i < n; ++i) {
    f[i] = bin(d[i]), ans += t - f[i] + 1;
    while (t && d[i] > a[t]) --t;
    a[++t] = d[i];
  }
  t = -0x7fffffff;
  for (int i = n - 1; i > 1; i--)
    ans += d[i] >= t && f[i] != 1, t = d[i] > t ? d[i] : t;
  printf("%I64d\n", ans);
}
