#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000 * 1000 + 6;
int a[MAXN], aa[MAXN], l[MAXN], r[MAXN], eq[MAXN];
stack<int> st;
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> aa[i];
  int imax = max_element(aa, aa + n) - aa;
  for (int i = imax; i < n; i++) a[i - imax] = aa[i];
  for (int i = 0; i < imax; i++) a[n - imax + i] = aa[i];
  a[n] = a[0];
  for (int i = 0; i <= n; i++) {
    while (!st.empty() && a[st.top()] <= a[i]) st.pop();
    if (st.empty())
      l[i] = -1;
    else
      l[i] = st.top();
    st.push(i);
  }
  while (!st.empty()) st.pop();
  for (int i = n; i >= 0; i--) {
    while (!st.empty() && a[st.top()] < a[i]) st.pop();
    if (st.empty())
      r[i] = n + 1;
    else
      r[i] = st.top();
    if (r[i] != n + 1 && a[r[i]] == a[i]) {
      eq[i] = eq[r[i]] + 1;
      r[i] = r[r[i]];
    }
    st.push(i);
  }
  long long ans = 0;
  for (int i = 1; i < n; i++) {
    if (r[i] != n + 1) ans++;
    if (l[i] != -1) ans++;
    if (l[i] == 0 && r[i] == n) ans--;
    ans += eq[i];
  }
  cout << ans << endl;
  return 0;
}
