#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
const int INF = 0x3f3f3f3f;
int a[N], l[N], q[N], en, pos[N];
long long ans;
void solve(int n) {
  for (int i = (1); i <= (n); i++) pos[abs(a[i])] = n + 1;
  q[en = 1] = 0;
  for (int i = (1); i <= (n); i++) {
    while (en && a[q[en]] <= a[i]) en--;
    l[i] = q[en];
    q[++en] = i;
  }
  q[en = 1] = n + 1;
  for (int i = (n); i >= (1); i--) {
    while (en && a[q[en]] <= a[i]) en--;
    int r = min(q[en], pos[abs(a[i])]);
    ans += 1ll * a[i] * (r - i) * (i - l[i]);
    q[++en] = i;
    pos[abs(a[i])] = i;
  }
}
int main() {
  int n;
  cin >> n;
  for (int i = (1); i <= (n); i++) scanf("%d", &a[i]);
  a[0] = a[n + 1] = INF;
  solve(n);
  for (int i = (1); i <= (n); i++) a[i] = -a[i];
  solve(n);
  cout << ans << endl;
  return 0;
}
