#include <bits/stdc++.h>
using namespace std;
struct M {
  int count;
  int height;
  M* next;
  M* prev;
};
int main() {
  int n;
  M* head = NULL;
  M* tail = NULL;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    M* m = new M();
    scanf("%d", &m->height);
    m->count = 1;
    m->next = NULL;
    m->prev = tail;
    if (tail) {
      tail->next = m;
      tail = m;
    } else {
      head = tail = m;
    }
  }
  head->prev = tail;
  tail->next = head;
  int64_t pairs = 0;
  while (true) {
    M* prev = head->prev;
    M* pp = prev->prev;
    if (prev == head) {
      delete head;
      break;
    }
    if (prev->height == head->height) {
      pairs += (int64_t)prev->count * (int64_t)head->count;
      head->count += prev->count;
      pp->next = head;
      head->prev = pp;
      delete prev;
      continue;
    }
    if (pp == head) {
      if (head->height < prev->height) {
        pp = head;
        head = prev;
        prev = pp;
      }
      pairs += (int64_t)prev->count * (int64_t)min(2, head->count);
      delete head;
      delete prev;
      break;
    }
    if ((pp->height > prev->height) && (prev->height < head->height)) {
      pairs += (int64_t)prev->count * 2;
      pp->next = head;
      head->prev = pp;
      delete prev;
      continue;
    }
    head = head->next;
  }
  printf("%" PRId64, pairs);
  return 0;
}
