#include <bits/stdc++.h>
using namespace std;
int n, ME = -1;
deque<int> R;
deque<int> fl, fr, eql, eqr;
vector<int> P;
int main() {
  scanf("%d", &n);
  R.resize(n);
  for (int i = 0; i < n; ++i) scanf("%d", &R[i]);
  ME = *max_element(R.begin(), R.end());
  while (R[0] != ME) {
    R.push_back(R[0]);
    R.pop_front();
  }
  int BRME = 0;
  for (int i = 0; i < R.size(); ++i)
    if (ME == R[i]) ++BRME;
  R.push_back(ME);
  R.push_front(2000000000);
  R.push_back(2000000000);
  fl.resize(R.size());
  fr.resize(R.size());
  eql.resize(R.size());
  eqr.resize(R.size());
  P.push_back(0);
  for (int i = 1; i < R.size() - 1; ++i) {
    while (R[P.back()] < R[i]) P.pop_back();
    if (R[P.back()] == R[i]) {
      eql[i] = 1 + eql[P.back()];
      P.pop_back();
    }
    fl[i] = P.back();
    P.push_back(i);
  }
  P.push_back(R.size() - 1);
  for (int i = R.size() - 2; i > 0; --i) {
    while (R[P.back()] < R[i]) P.pop_back();
    if (R[P.back()] == R[i]) {
      eqr[i] = 1 + eqr[P.back()];
      P.pop_back();
    }
    fr[i] = P.back();
    P.push_back(i);
  }
  long long ans = (BRME * (BRME - 1LL)) / 2;
  for (int i = 2; i < ((int)(R).size()) - 2; ++i) {
    if (R[i] == ME) continue;
    ans += eql[i] + 2;
    if (fl[i] == 1 && fr[i] == R.size() - 2) --ans;
  }
  cout << ans << '\n';
  return 0;
}
