#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000000 + 100;
int n, h[MAXN];
bool comp(int i, int j) { return h[i] < h[j]; }
deque<int> q;
int insert(int i) {
  if (!q.empty() && q.back() == i) q.pop_back();
  deque<int>::iterator it = upper_bound((q).begin(), (q).end(), i, comp);
  int res = it - q.begin() + (it != q.end());
  while (!q.empty() && h[q.front()] < h[i]) q.pop_front();
  q.push_front(i);
  return res;
}
int main() {
  cin >> n;
  for (int i = 0; i < (int)(n); i++) cin >> h[i];
  int big[3] = {-1, -1};
  for (int i = 0; i < (int)(n); i++) {
    big[2] = h[i];
    for (int j = 2; j > 0 && big[j - 1] < big[j]; j--) swap(big[j], big[j - 1]);
  }
  long long int c1 = count(h, h + n, big[0]), c2 = count(h, h + n, big[1]);
  long long int rest = (big[0] == big[1]) ? (c1 * (c1 - 1)) / 2 : c2;
  long long int res = 0;
  q.clear();
  for (int i = 0; i < (int)(n); i++) insert(i);
  for (int i = 0; i < (int)(n); i++) res += insert(i);
  cout << res - rest << endl;
  return 0;
}
