#include <bits/stdc++.h>
template <typename A, typename B>
inline bool mins(A &x, B y) {
  return (x > y) ? (x = y, 1) : 0;
}
template <typename A, typename B>
inline bool maxs(A &x, B y) {
  return (x < y) ? (x = y, 1) : 0;
}
using namespace std;
int n, mx = 0, c = 0, mx2 = 0, c2 = 0, p, h[1000001];
long long ans;
struct hill {
  int h;
  long long c;
  hill(){};
  hill(int x, long long y) {
    h = x;
    c = y;
  }
  bool operator<(hill z) const { return h != z.h ? h < z.h : c < z.c; }
} t;
stack<hill> S;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &h[i]);
    if (mx < h[i]) {
      mx = h[i];
      c = 1;
      p = i;
    } else if (mx == h[i]) {
      c++;
    }
  }
  if (c > 1) {
    ans = -2 * c;
  } else {
    for (int i = 1; i <= n; i++) {
      if (mx == h[i]) {
        continue;
      }
      if (mx2 < h[i]) {
        mx2 = h[i];
        c2 = 1;
      } else if (mx2 == h[i]) {
        c2++;
      }
    }
    ans = -2 - c2;
  }
  S.push(hill(h[p], 1));
  for (int i = p + 1; i <= n; i++) {
    t.h = h[i];
    t.c = 1;
    while (!S.empty() and S.top().h <= h[i]) {
      if (S.top().h == h[i]) {
        t.c += S.top().c;
      }
      ans += S.top().c;
      S.pop();
    }
    ans++;
    S.push(t);
  }
  for (int i = 1; i <= p; i++) {
    t.h = h[i];
    t.c = 1;
    while (!S.empty() and S.top().h <= h[i]) {
      if (S.top().h == h[i]) {
        t.c += S.top().c;
      }
      ans += S.top().c;
      S.pop();
    }
    ans++;
    S.push(t);
  }
  printf("%I64d ", ans);
  return 0;
}
