#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010;
int a[maxn], b[maxn], s[maxn], cnt[maxn];
int main() {
  int i, n, mx = 0, t = 0;
  long long nAns;
  scanf("%d", &n);
  nAns = n - 1;
  for (i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    if (a[i] > a[mx]) mx = i;
  }
  for (i = mx + 1; i <= n; i++) b[i - mx] = a[i];
  for (i = 1; i < mx; i++) b[n - mx + i] = a[i];
  for (i = 1; i < n; i++) {
    while (t && s[t] < b[i]) nAns += cnt[t--];
    if (!t || s[t] > b[i]) {
      s[++t] = b[i];
      cnt[t] = 0;
    }
    nAns += cnt[t];
    cnt[t]++;
  }
  for (i = 2; i <= t; i++) nAns += cnt[i];
  printf("%lld\n", nAns);
  return 0;
}
