#include <bits/stdc++.h>
using namespace std;
const int sz = 1e6 + 7;
int n, a[sz], l[sz], r[sz], x[sz], mxi;
long long c[sz], sum;
struct node {
  int v, no;
  long long num;
} q[sz];
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    if (a[i] > a[mxi]) mxi = i;
  }
  for (int i = 0; i < n; i++) x[(i - mxi + n) % n] = a[i];
  for (int i = n; i >= 1; i--) x[i] = x[i - 1];
  x[n + 1] = a[mxi];
  int rr = 0;
  for (int i = 1; i <= n + 1; i++) {
    for (;;) {
      if (rr == 0 || q[rr].v > x[i]) break;
      rr--;
    }
    l[i] = q[rr].no;
    q[++rr].v = x[i];
    q[rr].no = i;
  }
  rr = 0;
  for (int i = n + 1; i >= 1; i--) {
    for (;;) {
      if (rr == 0 || q[rr].v >= x[i]) break;
      rr--;
    }
    if (x[i] == q[rr].v)
      c[i] = q[rr].num, q[rr].num++, r[i] = r[q[rr].no], q[rr].no = i;
    else
      r[i] = q[rr].no, q[++rr].v = x[i], q[rr].no = i, q[rr].num = 1;
  }
  for (int i = 2; i <= n; i++) {
    if (!(l[i] == 1 && r[i] == n + 1)) {
      if (l[i] != 0) sum++;
      if (r[i] != 0) sum++;
    } else
      sum++;
    if (x[i] != a[mxi]) sum += c[i];
  }
  sum += (c[1] - 1) * c[1] / 2;
  printf("%lld", sum);
  return 0;
}
