#include <bits/stdc++.h>
using namespace std;
const int N_MAX = 1000000;
int n;
int h[N_MAX + 2];
int st[N_MAX + 2];
int lg;
int cntEqSt[N_MAX + 2];
bool ok[N_MAX + 2];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> h[i];
  int maxPos = 0;
  for (int i = 1; i <= n; i++)
    if (h[i] > h[maxPos]) maxPos = i;
  reverse(h + 1, h + maxPos + 1);
  reverse(h + maxPos + 1, h + n + 1);
  h[++n] = h[1];
  long long answer = 0;
  lg = 0;
  for (int i = 1; i < n; i++) {
    while (lg > 0 && h[st[lg]] < h[i]) lg--;
    if (h[i] == h[st[lg]])
      cntEqSt[i] = cntEqSt[st[lg]] + 1;
    else
      cntEqSt[i] = 1;
    answer += cntEqSt[i] - 1;
    if (lg > 0 && h[st[lg]] == h[i]) lg--;
    answer += (lg > 0);
    ok[i] = (lg > 0 && st[lg] == 1);
    st[++lg] = i;
  }
  lg = 0;
  for (int i = n; i >= 1; i--) {
    while (lg > 0 && h[st[lg]] <= h[i]) lg--;
    if (h[i] == h[st[lg]])
      cntEqSt[i] = cntEqSt[st[lg]] + 1;
    else
      cntEqSt[i] = 1;
    answer += (lg > 0 && !(st[lg] == n && ok[i] == true));
    st[++lg] = i;
  }
  cout << answer << "\n";
  return 0;
}
