#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000005;
int a[maxn], b[maxn], lef[maxn], rig[maxn], c[maxn] = {0};
int main() {
  int n;
  scanf("%d", &n);
  int ma = -1, mid = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    if (a[i] > ma) {
      ma = a[i];
      mid = i;
    }
  }
  mid--;
  for (int j = 1; j <= n; j++) b[j] = a[(mid + j) % n];
  lef[1] = 1;
  for (int i = 2; i <= n; i++) {
    lef[i] = i - 1;
    while (lef[i] > 1 && b[lef[i]] <= b[i]) lef[i] = lef[lef[i]];
  }
  for (int i = n; i >= 1; i--) {
    rig[i] = i + 1;
    while (rig[i] <= n && b[rig[i]] < b[i]) rig[i] = rig[rig[i]];
    if (rig[i] <= n && b[rig[i]] == b[i]) {
      c[i] = c[rig[i]] + 1;
      rig[i] = rig[rig[i]];
    }
  }
  long long ans = 0;
  for (int i = 2; i <= n; i++) {
    ans += c[i] + 2;
    if (lef[i] == 1 && rig[i] == n + 1) ans--;
  }
  printf("%lld\n", ans);
}
