#include <bits/stdc++.h>
using namespace std;
static const double EPS = 1e-10;
template <typename T, typename S>
vector<T> &operator<<(vector<T> &a, S b) {
  a.push_back(b);
  return a;
}
template <typename T>
void operator>>(vector<T> &a, int b) {
  while (b--)
    if (!a.empty()) a.pop_back();
}
bool isprime(int n) {
  if (n < 2) return false;
  for (int i = 2; i * i <= n; i++)
    if (n % i == 0) return false;
  return true;
}
long long b_pow(long long x, long long n) {
  return n ? b_pow(x * x, n / 2) * (n % 2 ? x : 1) : 1ll;
}
string itos(int n) {
  stringstream ss;
  ss << n;
  return ss.str();
}
long long v[1000010];
struct List {
  List *l, *r;
  long long c;
  long long x;
  int idx;
  List() { l = r = NULL; }
};
List lst[1000010] = {};
int idx[1000010];
int used[1000010] = {};
bool cmp(const int &a, const int &b) { return v[a] < v[b]; }
int main() {
  ios_base::sync_with_stdio(false);
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &v[i]);
  }
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    lst[i].l = &lst[(i - 1 + n) % n];
    lst[i].r = &lst[(i + 1) % n];
    lst[i].x = v[i];
    lst[i].c = 0;
    lst[i].idx = i;
    idx[i] = i;
  }
  sort(idx, idx + n, cmp);
  int U = n;
  for (int i = 0; i < n; i++) {
    if (used[idx[i]]) {
      continue;
    }
    List *start, *cur = &lst[idx[i]];
    long long counter = 0;
    while (cur->x == v[idx[i]] && (counter == 0 || cur != &lst[idx[i]])) {
      cur = cur->l;
      counter++;
    }
    counter = 0;
    if (cur->x != v[idx[i]]) cur = cur->r;
    start = cur;
    long long mult = 0;
    while (cur->x == start->x && (counter == 0 || cur != start)) {
      counter++;
      mult += cur->c;
      used[cur->idx] = true;
      cur = cur->r;
    };
    ans += mult;
    ans += counter * (counter - 1) / 2;
    (*start).l->c += counter;
    if ((*start).l != cur) (*cur).c += counter;
    (*start).l->r = cur;
    cur->l = (*start).l;
    U -= counter;
    if (U == 0) break;
  }
  cout << ans << endl;
}
