#include <bits/stdc++.h>
using namespace std;
int N;
int A[2000000], B[2000000];
int l[2000000], r[2000000], c[2000000];
int main() {
  scanf("%d", &N);
  int mxi = 0;
  for (int Ni = 0; Ni < N; Ni++) {
    scanf("%d", &A[Ni]);
    if (A[Ni] > A[mxi]) mxi = Ni;
  }
  for (int Ni = 0; Ni < N; Ni++) B[Ni] = A[(Ni + mxi) % N];
  B[N] = B[0];
  for (int Ni = N - 1; Ni >= 0; Ni--) {
    r[Ni] = Ni + 1;
    while (r[Ni] < N && B[Ni] > B[r[Ni]]) r[Ni] = r[r[Ni]];
    if (r[Ni] < N && B[Ni] == B[r[Ni]]) c[Ni] = c[r[Ni]] + 1, r[Ni] = r[r[Ni]];
  }
  for (int Ni = 1; Ni < N; Ni++) {
    l[Ni] = Ni - 1;
    while (l[Ni] > 0 && B[Ni] > B[l[Ni]]) l[Ni] = l[l[Ni]];
    if (l[Ni] > 0 && B[Ni] == B[l[Ni]]) l[Ni] = l[l[Ni]];
  }
  long long Ans = 0;
  for (int Ni = 0; Ni < N; Ni++) {
    if (B[Ni] == B[0])
      ;
    else if (l[Ni] == 0 && r[Ni] == N)
      Ans++;
    else
      Ans += 2;
    Ans += c[Ni];
  }
  printf("%I64d\n", Ans);
}
