#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18 + 2;
long long dmax;
stack<long long> qu;
long long lmin[1000005], rmin[1000005], a[1000005], lmax[1000005],
    rmax[1000005];
long long ans1, ans2;
int main() {
  long long n;
  cin >> n;
  for (long long i = 0; i < n; i++) {
    cin >> a[i];
  }
  lmin[0] = 0;
  qu.push(0);
  for (long long i = 1; i < n; i++) {
    while (!qu.empty() && a[qu.top()] >= a[i]) {
      qu.pop();
    }
    if (qu.empty()) {
      lmin[i] = 0;
    } else
      lmin[i] = qu.top() + 1;
    qu.push(i);
  }
  rmin[n - 1] = n - 1;
  while (!qu.empty()) qu.pop();
  qu.push(n - 1);
  for (long long i = n - 2; i >= 0; i--) {
    while (!qu.empty() && a[qu.top()] > a[i]) {
      qu.pop();
    }
    if (qu.empty()) {
      rmin[i] = n - 1;
    } else
      rmin[i] = qu.top() - 1;
    qu.push(i);
  }
  while (!qu.empty()) qu.pop();
  lmax[0] = 0;
  qu.push(0);
  for (long long i = 1; i < n; i++) {
    while (!qu.empty() && a[qu.top()] <= a[i]) {
      qu.pop();
    }
    if (qu.empty()) {
      lmax[i] = 0;
    } else
      lmax[i] = qu.top() + 1;
    qu.push(i);
  }
  rmax[n - 1] = n - 1;
  while (!qu.empty()) qu.pop();
  qu.push(n - 1);
  for (long long i = n - 2; i >= 0; i--) {
    while (!qu.empty() && a[qu.top()] < a[i]) {
      qu.pop();
    }
    if (qu.empty()) {
      rmax[i] = n - 1;
    } else
      rmax[i] = qu.top() - 1;
    qu.push(i);
  }
  for (long i = 0; i < n; i++) {
    long long x = i - lmax[i];
    long long y = rmax[i] - i;
    ans1 += (x * y + x + y) * a[i];
    x = (i - lmin[i]);
    y = rmin[i] - i;
    ans2 += (x * y + x + y) * a[i];
  }
  cout << ans1 - ans2;
}
