#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
inline void read(int& x) {
  static char c;
  while (!isdigit(c = getchar()))
    ;
  x = c ^ 48;
  while (isdigit(c = getchar())) x = (x * 10) + (c ^ 48);
}
int n, M, C;
int T[N], srt[N], H[N];
vector<int> Pos[N];
set<int> Occ;
set<int>::iterator it;
long long Ans;
inline void Work() {
  read(n);
  for (register int i = 1; i <= n; ++i) read(T[i]), srt[i] = T[i];
  sort(srt + 1, srt + n + 1), C = unique(srt + 1, srt + n + 1) - srt - 1;
  for (register int i = 1; i <= n; ++i) {
    T[i] = lower_bound(srt + 1, srt + C + 1, T[i]) - srt;
    if (T[i] > T[M]) M = i;
  }
  for (register int i = 1; i <= n; ++i)
    H[i] = T[(M + i - 2) % n + 1], Pos[H[i]].push_back(i);
  Occ.insert(n + 1);
  for (register int i = C; i; --i) {
    int cnt = 0, lst = 0;
    for (int P : Pos[i]) {
      it = Occ.lower_bound(P);
      if ((*it) ^ lst)
        Ans += 1ll * cnt * (cnt - 1) / 2, cnt = 1, lst = *it;
      else
        ++cnt;
      if (i == C) continue;
      if (*it <= n)
        Ans += 2;
      else if (*(--it) == 1)
        ++Ans;
      else
        Ans += 2;
    }
    Ans += 1ll * cnt * (cnt - 1) / 2;
    for (int P : Pos[i]) Occ.insert(P);
  }
  printf("%lld\n", Ans);
}
int main() { Work(); }
