#include <bits/stdc++.h>
using namespace std;
int val[1000020];
struct E {
  int to, same;
};
vector<E> graph[1000020];
long long connection(int id) {
  long long res = 1;
  for (__typeof((graph[id]).begin()) it = (graph[id]).begin();
       it != (graph[id]).end(); ++it)
    if (it->same) res += connection(it->to);
  return res;
}
long long dfs1(int id, long long depth) {
  long long res = 0;
  for (__typeof((graph[id]).begin()) it = (graph[id]).begin();
       it != (graph[id]).end(); ++it) {
    if (it->same)
      res += dfs1(it->to, 1);
    else {
      if (depth) res += connection(it->to);
      res += dfs1(it->to, 1);
    }
  }
  return res;
}
long long dfs2(int id, long long depth) {
  long long res = depth;
  for (__typeof((graph[id]).begin()) it = (graph[id]).begin();
       it != (graph[id]).end(); ++it) {
    if (it->same)
      res += dfs2(it->to, depth + 1);
    else
      res += dfs2(it->to, 0);
  }
  return res;
}
long long count_pairs(vector<int> &vh, int flag) {
  int N = (int)((vh).size());
  for (int j = 0; j < (int)(N + 1); ++j) graph[j].clear();
  map<int, int> mp;
  for (int j = 0; j < (int)(N); ++j) {
    map<int, int>::iterator it = mp.lower_bound(vh[j]);
    if (it == mp.end())
      graph[N].push_back((E){j, 0});
    else
      graph[it->second].push_back((E){j, (it->first == vh[j])});
    for (;;) {
      if ((int)((mp).size()) == 0 || mp.begin()->first >= vh[j]) break;
      mp.erase(mp.begin());
    }
    mp[vh[j]] = j;
  }
  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 j = 0; j < (int)((int)((vh).size())); ++j)
    if (vh[j] >= mm) res++, mm = vh[j];
  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;
  while (scanf("%d", &N) != EOF) {
    for (int j = 0; j < (int)(N); ++j) scanf("%d", val + j);
    long long res = 0;
    int highest = 0;
    for (int j = 0; j < (int)(N); ++j) highest = max(highest, val[j]);
    int start = -1;
    for (int j = 0; j < (int)(N); ++j)
      if (val[j] == highest) {
        start = j;
        break;
      }
    int prevh = start;
    long long highcnt = 0;
    vector<int> vh;
    for (int k = 0; k < (int)(N); ++k) {
      int id = (start + 1 + k) % N;
      if (val[id] == highest) {
        res += solve(vh);
        highcnt++;
        vh.clear();
      } else
        vh.push_back(val[id]);
    }
    res += highcnt * (highcnt - 1) / 2;
    if (highcnt == 1) {
      int secondh = 0;
      for (int j = 0; j < (int)(N); ++j)
        if (val[j] < highest) secondh = max(secondh, val[j]);
      for (int j = 0; j < (int)(N); ++j)
        if (val[j] == secondh) res--;
    }
    cout << res << endl;
  }
}
