#include <bits/stdc++.h>
int st[1000005][2];
int cs;
int N;
int in[1000005];
int nw[1000005];
int mx, idx;
long long ans;
int sam;
int main() {
  int i;
  scanf("%d", &N);
  for (i = 0; i < N; i++) scanf("%d", &in[i]);
  mx = -1;
  for (i = 0; i < N; i++) {
    if (in[i] > mx) {
      mx = in[i];
      idx = i;
    }
  }
  for (i = 0; i < N; i++) nw[i] = in[(idx + i) % N];
  st[0][0] = nw[0];
  st[0][1] = 1;
  cs++;
  sam = true;
  for (i = 1; i < N; i++) {
    while (st[cs - 1][0] < nw[i]) {
      ans += (long long)st[cs - 1][1];
      cs--;
    }
    if (st[cs - 1][0] == nw[i]) {
      if (cs - 1 == 0) sam = false;
      ans += (long long)st[cs - 1][1];
      st[cs - 1][1]++;
    } else {
      st[cs][0] = nw[i];
      st[cs][1] = 1;
      cs++;
    }
    if (cs > 1) ans++;
  }
  while (cs > 2) ans += (long long)st[cs - 1][1], cs--;
  if (!sam)
    while (cs > 1) ans += (long long)st[cs - 1][1], cs--;
  printf("%I64d\n", ans);
}
