#include <bits/stdc++.h>
using namespace std;
const long long N = 1e6 + 100, MOD = 1e9 + 9, INF = 1e9, SQ = 370, LOG = 20;
int n, m, x1, x2, z, t, y2, maxi, maxi2, mini, ptr, a[N], sz[N], par[N], p, q,
    k;
long long ans, sum1, sum2, x, y;
bool mark[N];
pair<int, int> pr[N];
int findpar(int x) { return (par[x] == x ? x : par[x] = findpar(par[x])); }
void merg(int x, int y) {
  x = findpar(x), y = findpar(y);
  if (sz[x] < sz[y]) swap(x, y);
  par[y] = x;
  sz[x] += sz[y];
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> pr[i].first;
    pr[i].second = i;
    sz[i] = 1, par[i] = i;
  }
  sort(pr, pr + n);
  for (int i = 0; i < n; i++) {
    sum1 = sum2 = 1;
    x = pr[i].second, y = pr[i].first;
    if (x == 0) {
      if (mark[x + 1]) {
        merg(x, x + 1);
      }
      sum2 = sz[findpar(x)];
    } else if (x == n - 1) {
      if (mark[x - 1]) {
        merg(x, x - 1);
      }
      sum1 = sz[findpar(x)];
    } else {
      if (mark[x + 1]) {
        sum1 += sz[findpar(x + 1)];
        merg(x, x + 1);
      }
      if (mark[x - 1]) {
        sum2 += sz[findpar(x - 1)];
        merg(x, x - 1);
      }
    }
    ans += sum1 * sum2 * y;
    mark[x] = true;
  }
  for (int i = 0; i < n; i++) {
    sz[i] = 1, par[i] = i, mark[i] = 0;
  }
  for (int i = n - 1; i >= 0; i--) {
    sum1 = sum2 = 1;
    x = pr[i].second, y = pr[i].first;
    if (x == 0) {
      if (mark[x + 1]) {
        merg(x, x + 1);
      }
      sum2 = sz[findpar(x)];
    } else if (x == n - 1) {
      if (mark[x - 1]) {
        merg(x, x - 1);
      }
      sum1 = sz[findpar(x)];
    } else {
      if (mark[x + 1]) {
        sum1 += sz[findpar(x + 1)];
        merg(x, x + 1);
      }
      if (mark[x - 1]) {
        sum2 += sz[findpar(x - 1)];
        merg(x, x - 1);
      }
    }
    ans -= sum1 * sum2 * y;
    mark[x] = true;
  }
  cout << ans;
}
