#include <bits/stdc++.h>
using namespace std;
int n, i, k, a[1000010], b[1000010], l[1000010], r[1000010], c[1000010];
long long ans;
int main() {
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    if (a[k] < a[i]) k = i;
  }
  for (i = k; i < n; i++) b[i - k] = a[i];
  for (i = 0; i < k; i++) b[n - k + i] = a[i];
  for (i = 0; i < n; i++) a[i] = b[i];
  a[n] = a[0];
  for (i = n - 1; i >= 0; i--) {
    r[i] = i + 1;
    while (r[i] < n && a[i] > a[r[i]]) r[i] = r[r[i]];
    if (r[i] < n && a[r[i]] == a[i]) {
      c[i] = c[r[i]] + 1;
      r[i] = r[r[i]];
    }
  }
  for (i = 0; i < n; i++) {
    ans += c[i];
    if (a[i] == a[0]) continue;
    l[i] = i - 1;
    while (l[i] > 0 && a[i] > a[l[i]]) l[i] = l[l[i]];
    if (l[i] > 0 && a[l[i]] == a[i]) l[i] = l[l[i]];
    if (l[i] == 0 && r[i] == n)
      ans++;
    else
      ans += 2;
  }
  cout << ans;
}
