#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 600;
inline int read() {
  char ch;
  while ((ch = getchar()) < '0' || ch > '9')
    ;
  int res = ch - '0';
  while ((ch = getchar()) >= '0' && ch <= '9') res = res * 10 + ch - '0';
  return res;
}
long long ans;
int cn[N], r[N], l[N], stk[N], top, n;
int a[N], d[N], st;
int main() {
  n = read();
  for (int i = 1; i <= n; i++) {
    a[i] = read();
    if (a[st] < a[i]) st = i;
  }
  for (int i = st, j = 0; j <= n; i = i % n + 1, j++) d[j] = a[i];
  for (int i = 0; i <= n; i++) {
    while (top && d[stk[top]] <= d[i]) top--;
    if (top)
      l[i] = stk[top];
    else
      l[i] = -1;
    stk[++top] = i;
  }
  top = 0;
  for (int i = n; i >= 0; i--) {
    while (top && d[stk[top]] < d[i]) top--;
    if (!top || d[stk[1]] == d[i])
      r[i] = -1, cn[i] = top;
    else {
      int l = 1, r = top;
      while (l <= r) {
        int mid = l + r >> 1;
        if (d[stk[mid]] > d[i])
          l = mid + 1;
        else
          r = mid - 1;
      }
      ::r[i] = stk[l - 1];
      cn[i] = top - l + 1;
    }
    stk[++top] = i;
  }
  for (int i = 0; i <= n; i++) {
    if (l[i] != -1) ans++;
    if (r[i] != -1 && (r[i] != n || l[i] != 0)) ans++;
    if (i != 0) ans += cn[i];
  }
  printf("%lld", ans);
  return 0;
}
