#include <bits/stdc++.h>
using namespace std;
template <typename T>
bool checkmax(T &a, const T &b) {
  return b > a ? (a = b, true) : false;
}
int ar[1000010], tar[1000010], l[1000010], r[1000010], c[1000010];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) scanf("%d", ar + i);
  int a = 0, b = 1, t;
  while (true) {
    t = 0;
    while (t < n && ar[(a + t) % n] == ar[(b + t) % n]) ++t;
    if (t == n) break;
    if (ar[(a + t) % n] > ar[(b + t) % n])
      b += t + 1;
    else
      a += t + 1;
    if (a > b) swap(a, b);
    if (a == b) ++b;
    if (b >= n) break;
  }
  for (t = 0; a + t < n; ++t) tar[t] = ar[a + t];
  for (int i = 0; i < a; ++i, ++t) tar[t] = ar[i];
  tar[n] = tar[0];
  long long ans = 0, tc = 0;
  for (int i = n - 1; i >= 0; --i) {
    if (tar[i] == tar[0]) {
      ++tc;
      continue;
    }
    t = i + 1;
    while (tar[i] > tar[t]) t = r[t];
    if (tar[i] == tar[t]) {
      c[i] = c[t] + 1;
      t = r[t];
    } else
      c[i] = 0;
    r[i] = t;
    ans += c[i];
  }
  for (int i = 1; i < n; ++i) {
    if (tar[i] == tar[0]) continue;
    t = i - 1;
    while (tar[i] >= tar[t]) t = l[t];
    l[i] = t;
    if (l[i] == 0 && r[i] == n)
      ans += 1;
    else
      ans += 2;
  }
  ans += tc * (tc - 1) / 2;
  printf("%I64d\n", ans);
}
