#include <bits/stdc++.h>
using namespace std;
template <class T>
inline string itos(T n) {
  return (n) < 0    ? "-" + itos(-(n))
         : (n) < 10 ? (string)("") + (char)('0' + (n))
                    : itos((n) / 10) + itos((n) % 10);
}
int N;
pair<int, int> p[1000010];
set<int> s;
int main(void) {
  int i, j, k;
  scanf("%d", &N);
  for ((i) = 0; (i) < (int)(N); (i)++) scanf("%d", &p[i].first);
  int tmp = 0;
  for ((i) = 0; (i) < (int)(N); (i)++)
    if (p[i].first > p[tmp].first) tmp = i;
  for ((i) = 0; (i) < (int)(N); (i)++) p[i].second = (i - tmp + N) % N;
  for ((i) = 0; (i) < (int)(N); (i)++) p[i].first = -p[i].first;
  sort(p, p + N);
  long long ans = 0;
  i = 0;
  while (i < N) {
    int sz = s.size();
    for (j = i; j < N; j++)
      if (p[j].first != p[i].first) break;
    int prev = -1, cnt = 0;
    if (sz == 0) ans += (long long)(j - i) * (long long)(j - i - 1) / 2;
    if (sz != 0)
      for (k = j - 1; k >= i; k--) {
        int cur = *(--s.lower_bound(p[k].second));
        if (cur != prev) {
          prev = cur;
          ans += (long long)cnt * (long long)(cnt - 1) / 2 +
                 (long long)cnt * min(sz, 2);
          cnt = 0;
        }
        cnt++;
      }
    ans +=
        (long long)cnt * (long long)(cnt - 1) / 2 + (long long)cnt * min(sz, 2);
    for (k = i; k < j; k++) s.insert(p[k].second);
    i = j;
  }
  cout << ans << endl;
  return 0;
}
