#include <bits/stdc++.h>
using namespace std;
const int G = 1000 * 1000 + 10;
int a[G], b[G], l[G], r[G], brbr[G];
stack<pair<int, int>> cnex, cper;
int main() {
  int n;
  cin >> n;
  int mx = 0;
  for (int i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] > b[mx]) mx = i;
  }
  int y = 1;
  a[0] = b[mx];
  a[n] = b[mx];
  for (int i = mx + 1; i <= n; i++) {
    a[y] = b[i];
    y++;
  }
  for (int i = 1; i < mx; i++) {
    a[y] = b[i];
    y++;
  }
  cnex.push(make_pair(a[n], n));
  r[n] = n + 1;
  r[0] = n + 1;
  for (int i = n - 1; i > 0; i--) {
    while (cnex.size() && cnex.top().first < a[i]) {
      cnex.pop();
    }
    int u = cnex.top().second;
    if (cnex.size()) {
      if (a[i] == cnex.top().first) {
        brbr[i] = brbr[cnex.top().second] + 1;
        r[i] = r[u];
      } else {
        r[i] = u;
      }
    } else
      r[i] = n + 1;
    cnex.push(make_pair(a[i], i));
  }
  cper.push(make_pair(a[0], 0));
  l[0] = -1;
  l[n] = -1;
  for (int i = 1; i < n; i++) {
    while (cper.size() && cper.top().first <= a[i]) {
      cper.pop();
    }
    if (cper.size() && a[i] != cper.top().first)
      l[i] = cper.top().second;
    else
      l[i] = -1;
    cper.push(make_pair(a[i], i));
  }
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    if (l[i] != -1) {
      if (l[i] != 0 || r[i] != n) {
        ans++;
      }
    }
    if (r[i] != n + 1) {
      ans++;
    }
    ans += brbr[i];
  }
  cout << ans << endl;
  return 0;
}
