#include <bits/stdc++.h>
const int oo = 0x3f3f3f3f;
template <typename T>
bool chkmax(T &a, T b) {
  return a < b ? a = b, true : false;
}
template <typename T>
bool chkmin(T &a, T b) {
  return a > b ? a = b, true : false;
}
template <typename T>
void read(T &x) {
  char ch = getchar();
  while (!isdigit(ch)) ch = getchar();
  for (x = 0; isdigit(ch); ch = getchar()) x = 10 * x + ch - '0';
}
const int MAXN = 1e6 + 5;
int N, A[MAXN];
void input() {
  read(N);
  for (int i = 1; i <= N; i++) {
    read(A[i]);
  }
}
void solve() {
  static int st[MAXN], cnt[MAXN];
  static bool flag[MAXN];
  std::rotate(A + 1, std::max_element(A + 1, A + N + 1), A + N + 1);
  int top = 0;
  long long ans = 0;
  st[top] = 1;
  for (int i = 2; i <= N; i++) {
    for (; A[st[top]] < A[i]; top--) {
      ans++;
    }
    if (A[st[top]] == A[i]) ans += cnt[i] = cnt[st[top]] + 1;
    if (top - cnt[i] >= 0) {
      ans++;
      flag[i] = top - cnt[i] > 0;
    }
    st[++top] = i;
  }
  for (; top > 0; top--) {
    if (flag[st[top]]) ans++;
  }
  std::cout << ans << std::endl;
}
int main() {
  input();
  solve();
  return 0;
}
