#include <bits/stdc++.h>
using namespace std;
const int N = 1000003;
int a[N];
int l[N];
int c[N];
int r[N];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) scanf("%d", a + i);
  rotate(a, max_element(a, a + n), a + n);
  long long res = 0;
  c[0] = 1;
  for (int i = 1; i < n; ++i) {
    int j = i - 1;
    while (a[j] < a[i]) j = l[j];
    l[i] = j;
    if (a[j] > a[i]) {
      ++res;
      c[i] = 2;
    } else {
      res += c[j];
      c[i] = c[j] + 1;
      l[i] = l[j];
    }
  }
  a[n] = a[0] + 1;
  for (int i = n - 1; i > 0; --i) {
    int j = i + 1;
    while (a[j] <= a[i]) j = r[j];
    r[i] = j;
    if (j != n || (a[i] != a[0] && l[i] != 0)) ++res;
  }
  printf("%lld\n", res);
  return 0;
}
