#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T& s) {
  s = 0;
  int f = 0;
  char c = getchar();
  while (!isdigit(c)) f |= (c == '-'), c = getchar();
  while (isdigit(c)) s = s * 10 + (c ^ 48), c = getchar();
  s = f ? -s : s;
}
const int _ = 1000000 + 10;
int n, a[_], s[_];
int top, st[_], cnt[_], vis[_];
int main() {
  read(n);
  for (register int i = 1; i <= n; ++i) read(a[i]), cnt[i] = 0, vis[i] = 0;
  int mp = 0, len = 0;
  for (register int i = 1; i <= n; ++i)
    if (a[i] > a[mp]) mp = i;
  for (register int i = mp + 1; i <= n; ++i) s[++len] = a[i];
  for (register int i = 1; i <= mp - 1; ++i) s[++len] = a[i];
  long long ans = 0;
  top = 0;
  for (register int i = 1; i <= len; ++i) {
    while (top && s[st[top]] <= s[i]) {
      if (s[st[top]] == s[i]) cnt[i] = cnt[st[top]] + 1;
      --top;
    }
    if (top) ++ans;
    st[++top] = i;
  }
  top = 0;
  for (register int i = len; i >= 1; --i) {
    while (top && s[st[top]] <= s[i]) --top;
    if (top) ++ans;
    st[++top] = i;
  }
  for (register int i = 1; i <= len; ++i) ans += cnt[i];
  int mid = 0;
  for (register int i = 1; i <= len; ++i)
    if (s[i] >= mid) ans += !vis[i], vis[i] = 1, mid = s[i];
  mid = 0;
  for (register int i = len; i >= 1; --i)
    if (s[i] >= mid) ans += !vis[i], vis[i] = 1, mid = s[i];
  printf("%lld\n", ans);
  return 0;
}
