#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int val[maxn];
struct edge {
  int to, same;
  edge() {}
  edge(int to, int same) : to(to), same(same) {}
};
vector<edge> g[maxn];
long long con(int id) {
  long long res = 1;
  for (int i = (0); i < (int)(g[id].size()); ++i)
    if (g[id][i].same) res += con(g[id][i].to);
  return res;
}
long long dfs1(int id, long long dep) {
  long long res = 0;
  for (int i = (0); i < (int)(g[id].size()); ++i) {
    if (g[id][i].same)
      res += dfs1(g[id][i].to, 1);
    else {
      if (dep) res += con(g[id][i].to);
      res += dfs1(g[id][i].to, 1);
    }
  }
  return res;
}
long long dfs2(int id, long long dep) {
  long long res = dep;
  for (int i = (0); i < (int)(g[id].size()); ++i) {
    if (g[id][i].same)
      res += dfs2(g[id][i].to, dep + 1);
    else
      res += dfs2(g[id][i].to, 0);
  }
  return res;
}
long long count_pairs(vector<int> &vh, int flag) {
  int n = vh.size();
  for (int i = (0); i < (int)(n + 1); ++i) g[i].clear();
  map<int, int> make_pair;
  for (int i = (0); i < (int)(n); ++i) {
    map<int, int>::iterator it = make_pair.lower_bound(vh[i]);
    if (it == make_pair.end())
      g[n].push_back(edge(i, 0));
    else
      g[it->second].push_back(edge(i, (it->first == vh[i])));
    for (;;) {
      if (make_pair.empty() || make_pair.begin()->first >= vh[i]) break;
      make_pair.erase(make_pair.begin());
    }
    make_pair[vh[i]] = i;
  }
  long long res = 0;
  res += dfs1(n, 0);
  if (flag) res += dfs2(n, 0);
  return res;
}
long long count_outside(vector<int> &vh) {
  long long res = 0;
  int mm = 0;
  for (int i = (0); i < (int)(vh.size()); ++i)
    if (vh[i] >= mm) res++, mm = vh[i];
  return res;
}
long long solve(vector<int> &vh) {
  long long res = 0;
  res += count_pairs(vh, 1);
  res += count_outside(vh);
  reverse(vh.begin(), vh.end());
  res += count_pairs(vh, 0);
  res += count_outside(vh);
  return res;
}
int main() {
  int n;
  scanf("%d", &n);
  int mxh = 0;
  for (int i = (0); i < (int)(n); ++i) {
    scanf("%d", val + i);
    if (val[i] > val[mxh]) mxh = i;
  }
  long long res = 0;
  int pre = mxh;
  long long cnt = 0;
  vector<int> vh;
  for (int i = (0); i < (int)(n); ++i) {
    int ii = (mxh + i + 1) % n;
    if (val[ii] == val[mxh]) {
      res += solve(vh);
      cnt++;
      vh.clear();
    } else
      vh.push_back(val[ii]);
  }
  res += cnt * (cnt - 1) / 2;
  if (cnt == 1) {
    int ndh = 0;
    for (int i = (0); i < (int)(n); ++i)
      if (val[i] < val[mxh]) ndh = max(ndh, val[i]);
    for (int i = (0); i < (int)(n); ++i)
      if (val[i] == ndh) res--;
  }
  printf("%I64d\n", res);
  return 0;
}
