#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:256000000")
using namespace std;
const int INF = 1000 * 1000 * 1000;
const double EPS = 1e-9;
const int MAXN = 1001001;
int a[MAXN << 1];
pair<int, int> st[MAXN];
bool used[MAXN];
int N;
int pt;
void clear() { pt = 0; }
void push(pair<int, int> x) { st[pt++] = x; }
void pop() { --pt; }
bool empty() { return pt == 0; }
void inc(int &x) { x = (x + 1) % N; }
void dec(int &x) { x = (x - 1 + N) % N; }
int main() {
  scanf("%d", &N);
  for (int i = 0; i < N; ++i) {
    scanf("%d", &a[i]);
    a[N + i] = a[i];
  }
  int maxVal = *max_element(a, a + N);
  int pos = -1;
  for (int i = 0; i < N; ++i)
    if (a[i] == maxVal) {
      pos = i;
      break;
    }
  for (int i = 0; i < N; ++i) {
    a[i] = a[i + pos];
  }
  long long res = 0;
  for (int i = 0; i < N; ++i)
    if (a[i] == maxVal) {
      clear();
    } else {
      while (!empty() && st[pt - 1].first < a[i]) {
        res += st[pt - 1].second;
        pop();
      }
      if (!empty())
        if (st[pt - 1].first > a[i]) {
          ++res;
        } else {
          res += st[pt - 1].second;
          if (pt > 1) {
            ++res;
          }
        }
      if (!empty() && st[pt - 1].first == a[i]) {
        ++st[pt - 1].second;
      } else {
        push(make_pair(a[i], 1));
      }
    }
  int cnt = 0;
  for (int i = 0; i < N; ++i)
    if (a[i] == maxVal) {
      ++cnt;
    }
  res += 1LL * cnt * (cnt - 1) / 2;
  if (cnt == 1) {
    int mx = -1;
    int k = 0;
    for (int i = 0; i + 1 < N; ++i) {
      dec(k);
      if (a[k] >= mx) {
        mx = a[k];
        used[k] = true;
        ++res;
      }
    }
    mx = -1;
    k = 0;
    for (int i = 0; i + 1 < N; ++i) {
      inc(k);
      if (a[k] >= mx) {
        mx = a[k];
        if (!used[k]) {
          ++res;
        }
      }
    }
  } else {
    for (int i = 0; i < N; ++i)
      if (a[i] == maxVal) {
        int k = i;
        dec(k);
        if (a[k] != maxVal) {
          ++res;
          int mx = a[k];
          dec(k);
          while (a[k] != maxVal) {
            if (a[k] >= mx) {
              ++res;
              mx = a[k];
            }
            dec(k);
          }
        }
        k = i;
        inc(k);
        if (a[k] != maxVal) {
          ++res;
          int mx = a[k];
          inc(k);
          while (a[k] != maxVal) {
            if (a[k] >= mx) {
              ++res;
              mx = a[k];
            }
            inc(k);
          }
        }
      }
  }
  printf("%I64d", res);
  return 0;
}
