#include <bits/stdc++.h>
using namespace std;
int n;
int a[2000005];
int *A = a;
int ff[3];
int main() {
  ios::sync_with_stdio(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    a[i + n] = a[i];
    ff[0] = a[i];
    sort(ff, ff + 3);
    if (a[i] > *A) {
      A = a + i;
    }
  }
  long long ans = 0;
  A++;
  for (int FAQ = 0; FAQ < 2; FAQ++) {
    stack<pair<int, int> > stk;
    for (int i = 0; i < n; i++) {
      while (stk.size()) {
        if (A[stk.top().first] < A[i]) {
          stk.pop();
          ans++;
        } else {
          break;
        }
      }
      if (stk.size() && A[stk.top().first] == A[i] && FAQ) {
        ans += stk.top().second;
        stk.push(make_pair(i, stk.top().second + 1));
      } else {
        stk.push(make_pair(i, 1));
      }
    }
    reverse(A, A + n - 1);
  }
  if (count(A, A + n, ff[2]) == 1) {
    ans -= count(A, A + n, ff[1]);
  }
  cout << ans << endl;
  return 0;
}
