#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (n); i++)
#define repr(i, n) for (int i = (n) - 1; i >= 0; i--)
#define range(a) a.begin(), a.end()

list<int> L[100000], R[100000];
int par[100000];

int find(int x) {
  if (par[x] == x) return x;
  return par[x] = find(par[x]);
}

void unite(int x, int y) {
  x = find(x);
  y = find(y);
  while (not L[x].empty() and not L[y].empty() and L[x].back() < L[y].front()) L[x].pop_back();
  while (not R[x].empty() and not R[y].empty() and R[x].back() > R[y].front()) R[y].pop_front();
  L[x].splice(L[x].end(), move(L[y]));
  R[x].splice(R[x].end(), move(R[y]));
  par[y] = x;
}

int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  int N; cin >> N;
  vector<int> A(N); rep(i, N) cin >> A[i], A[i]--;
  vector<int> ord(N); rep(i, N) ord[i] = i;
  sort(range(ord), [&](int i, int j) { return A[i] > A[j]; });
  rep(i, N) {
    L[i].push_back(A[i]);
    R[i].push_back(A[i]);
    par[i] = i;
  }
  ll ans = 0;
  for (int i : ord) {
    if (i - 1 >= 0 and A[i - 1] > A[i]) {
      ans += L[find(i - 1)].size();
      unite(i - 1, i);
    }
    if (i + 1 < N and A[i] < A[i + 1]) {
      ans += R[find(i + 1)].size();
      unite(i, i + 1);
    }
  }
  cout << ans << endl;
}