#include <bits/stdc++.h>
int a[1000100], b[1000100];
int sta[1000100];
int main(void) {
  int n, i;
  int aa, bb;
  int max, nmax, pmax;
  long long ans;
  int np;
  int p1, p2, p12;
  while (scanf("%d", &n) != EOF) {
    max = 0;
    for (i = 1; i <= n; i++) {
      scanf("%d", &bb);
      b[i] = bb;
      if (bb > max) {
        max = bb;
        nmax = 1;
        pmax = i;
      } else if (bb == max) {
        nmax++;
      }
    }
    for (i = 1; i <= n; i++) {
      a[i] = b[(i + pmax - 2) % n + 1];
    }
    ans = 0;
    np = 1;
    sta[1] = a[1];
    sta[0] = 2000000000;
    for (i = 2; i <= n; i++) {
      aa = a[i];
      if (aa >= sta[1]) {
        ans += np;
      } else if (aa < sta[np]) {
        ans += 1;
      } else {
        p1 = 1;
        p2 = np;
        while (p1 < p2) {
          p12 = (p1 + p2) / 2;
          if (aa < sta[p12]) {
            p1 = p12 + 1;
          } else {
            p2 = p12;
          }
        }
        ans += np - p1 + 2;
      }
      while (aa > sta[np]) {
        np--;
      }
      sta[++np] = aa;
    }
    if (nmax == 1) {
      if (np != 1) {
        aa = sta[2];
        for (i = 3; i <= np; i++) {
          if (sta[i] != aa) {
            ans++;
          }
        }
      }
    } else {
      aa = sta[1];
      for (i = 2; i <= np; i++) {
        if (sta[i] != aa) {
          ans++;
        }
      }
    }
    printf("%I64d\n", ans);
  }
  return 0;
}
