#include <bits/stdc++.h>
using namespace std;
unsigned int N;
unsigned int h[1000100], c[1000100], r[1000100];
long long ans = 0;
long long temp = 0;
int main() {
  cin >> N;
  int i = 0;
  for (i; i < N; i++) {
    cin >> h[i];
    c[i] = 1;
  }
  rotate<unsigned int*>(h, max_element<unsigned int*>(h, h + N), h + N);
  r[0] = 0;
  i = 1;
  for (i = 1; i < N; i++) {
    r[i] = i - 1;
    while ((h[i] > h[r[i]]) && (r[i] != 0)) {
      temp = c[r[i]];
      ans += 2 * temp + (((temp) * ((temp)-1)) >> 1);
      r[i] = r[r[i]];
    }
    if ((h[i] == h[r[i]]) && (r[i] != 0)) {
      c[i] += c[r[i]];
      r[i] = r[r[i]];
    }
  }
  i = N - 1;
  while (true) {
    temp = c[i];
    if (r[i] == 0) {
      ans += temp + (((temp) * ((temp)-1)) >> 1);
      break;
    }
    ans += 2 * temp + (((temp) * ((temp)-1)) >> 1);
    i = r[i];
  }
  cout << ans;
  return 0;
}
