#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:200000000")
using namespace std;
template <typename T>
inline T Abs(T x) {
  return (x >= 0) ? x : -x;
}
template <typename T>
inline T sqr(T x) {
  return x * x;
}
template <typename T>
string toStr(T x) {
  stringstream st;
  st << x;
  string s;
  st >> s;
  return s;
}
inline int nextInt() {
  int x;
  if (scanf("%d", &x) != 1) throw;
  return x;
}
inline long long nextInt64() {
  long long x;
  if (scanf("%I64d", &x) != 1) throw;
  return x;
}
inline double nextDouble() {
  double x;
  if (scanf("%lf", &x) != 1) throw;
  return x;
}
const int INF = (int)1E9;
const long long INF64 = (long long)1E18;
const long double EPS = 1E-9;
const long double PI = 3.1415926535897932384626433832795;
const int MAXN = 3000100;
int n, a[MAXN], l[MAXN], r[MAXN];
int tree[MAXN];
int get(int x) {
  int ans = 0;
  if (x < 0) return ans;
  for (; x >= 0; x = (x & (x + 1)) - 1) ans += tree[x];
  return ans;
}
int get(int l, int r) {
  int ans = get(r);
  if (l > 0) ans -= get(l - 1);
  return ans;
}
void update(int x, int value) {
  for (; x < 3 * n; x = (x | (x + 1))) tree[x] += value;
}
int main() {
  n = nextInt();
  for (int i = 0; i < (int)(n); i++) a[i + n] = a[i + 2 * n] = a[i] = nextInt();
  int n1 = n / 2, n2 = n - n1;
  vector<pair<int, int> > st;
  for (int i = 0; i < (int)(3 * n); i++) {
    while (!st.empty() && st.back().first <= a[i]) st.pop_back();
    if (st.empty())
      l[i] = i - n1 + 1;
    else
      l[i] = st.back().second;
    st.push_back(make_pair(a[i], i));
  }
  st.clear();
  for (int i = (int)(3 * n) - 1; i >= 0; i--) {
    while (!st.empty() && st.back().first <= a[i]) st.pop_back();
    if (st.empty())
      r[i] = i + n2;
    else
      r[i] = st.back().second;
    st.push_back(make_pair(a[i], i));
  }
  st.clear();
  for (int i = 0; i < (int)(n); i++) {
    update(i, +1);
    update(i + n, +1);
    update(i + 2 * n, +1);
    st.push_back(make_pair(a[i], i));
  }
  long long ans = 0;
  sort((st).begin(), (st).end());
  for (int i = 0; i < (int)(n); i++) {
    int x = st[i].second;
    int ll = l[x + n], rr = r[x + n];
    if ((ll % n) == (rr % n)) ll++;
    update(x, -1);
    update(x + n, -1);
    update(x + 2 * n, -1);
    ans += get(ll, rr);
  }
  cout << ans << endl;
  return 0;
}
