#include <bits/stdc++.h>
using namespace std;
const long long N = 1e6 + 10;
long long n, a[N], l[N], r[N], ans;
stack<long long> z;
int main() {
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]);
  a[n + 1] = 0x3f3f3f3f;
  n++;
  for (long long i = 1; i <= n; i++) {
    long long sum = 0;
    while (!z.empty()) {
      if (a[z.top()] <= a[i]) {
        z.pop();
      } else {
        sum = z.top();
        break;
      }
    }
    z.push(i);
    l[i] = sum;
  }
  while (!z.empty()) z.pop();
  for (long long i = n; i >= 1; i--) {
    long long sum = 0;
    while (!z.empty()) {
      if (a[z.top()] < a[i]) {
        z.pop();
      } else {
        sum = z.top();
        break;
      }
    }
    z.push(i);
    r[i] = sum;
  }
  n--;
  for (long long i = 1; i <= n; i++) ans += (r[i] - i) * (i - l[i]) * a[i];
  a[n + 1] = 0;
  n++;
  while (!z.empty()) z.pop();
  for (long long i = 1; i <= n; i++) {
    long long sum = 0;
    while (!z.empty()) {
      if (a[z.top()] >= a[i]) {
        z.pop();
      } else {
        sum = z.top();
        break;
      }
    }
    z.push(i);
    l[i] = sum;
  }
  while (!z.empty()) z.pop();
  for (long long i = n; i >= 1; i--) {
    long long sum = 0;
    while (!z.empty()) {
      if (a[z.top()] > a[i]) {
        z.pop();
      } else {
        sum = z.top();
        break;
      }
    }
    z.push(i);
    r[i] = sum;
  }
  n--;
  for (long long i = 1; i <= n; i++) ans -= (r[i] - i) * (i - l[i]) * a[i];
  printf("%lld\n", ans);
  return 0;
}
