#include <bits/stdc++.h>
const double PI = acos(-1.0);
using namespace std;
const long long MAXN = 1e6 + 5;
const long long INF = 1e9;
long long n;
long long a[MAXN], leftSmall[MAXN], rightSmall[MAXN], leftBig[MAXN],
    rightBig[MAXN];
long long C[MAXN];
long long CC(long long k, long long tn) {
  C[0] = 1;
  for (long long i = 1; i <= k; i++) C[i] = C[i - 1] * (tn - i + 1) / i;
  return C[k];
}
int main() {
  while (scanf("%lld", &n) == 1) {
    for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]);
    a[0] = a[n + 1] = INF;
    for (long long i = 1; i <= n; i++) {
      leftSmall[i] = i;
      while (a[i] > a[leftSmall[i] - 1])
        leftSmall[i] = leftSmall[leftSmall[i] - 1];
    }
    for (long long i = n; i >= 1; i--) {
      rightSmall[i] = i;
      while (a[i] >= a[rightSmall[i] + 1])
        rightSmall[i] = rightSmall[rightSmall[i] + 1];
    }
    a[0] = a[n + 1] = -INF;
    for (long long i = 1; i <= n; i++) {
      leftBig[i] = i;
      while (a[i] < a[leftBig[i] - 1]) leftBig[i] = leftBig[leftBig[i] - 1];
    }
    for (long long i = n; i >= 1; i--) {
      rightBig[i] = i;
      while (a[i] <= a[rightBig[i] + 1])
        rightBig[i] = rightBig[rightBig[i] + 1];
    }
    long long ans = 0;
    for (long long i = 1; i <= n; i++)
      ans += a[i] * ((i - leftSmall[i] + 1) * (rightSmall[i] - i + 1) -
                     (i - leftBig[i] + 1) * (rightBig[i] - i + 1));
    printf("%lld", ans);
  }
  return 0;
}
