#include <bits/stdc++.h>
using namespace std;
int a[2000000 + 5];
int l[2000000 + 5], r[2000000 + 5], sta[2000000 + 5], top;
int cntl[2000000 + 5], cntr[2000000 + 5];
int main() {
  memset(l, 63, sizeof l);
  memset(r, 63, sizeof r);
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= n; i++) a[i + n] = a[i];
  int M = 0;
  for (int i = 1; i <= n; i++) M = max(M, a[i]);
  for (int i = 1; i <= n * 2; i++) {
    while (top > 0 && a[sta[top]] < a[i]) {
      r[sta[top]] = i - sta[top];
      if (top - 1 > 0 && a[sta[top]] == a[sta[top - 1]])
        cntr[sta[top - 1]] = cntr[sta[top]] + 1;
      top--;
    }
    sta[++top] = i;
  }
  top = 0;
  for (int i = n * 2; i >= 1; i--) {
    while (top > 0 && a[sta[top]] < a[i]) {
      l[sta[top]] = sta[top] - i;
      if (top - 1 > 0 && a[sta[top]] == a[sta[top - 1]])
        cntl[sta[top - 1]] = cntl[sta[top]] + 1;
      top--;
    }
    sta[++top] = i;
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++)
    if (a[i] == M) ans++;
  ans = ans * (ans - 1);
  for (int i = 1; i <= n; i++)
    if (a[i] != M) ans += cntr[i] + cntl[i + n];
  ans /= 2;
  for (int i = 1; i <= n; i++)
    if (r[i] + l[i + n] == n)
      ans += 1;
    else if (r[i] + l[i + n] < n)
      ans += 2;
  printf("%I64d\n", ans);
  return 0;
}
