#include <bits/stdc++.h>
using namespace std;
const long long N = 1e6 + 7;
long long a[N];
long long l[N];
long long r[N];
int32_t main() {
  long long ans = 0, n, i;
  for (i = 1, scanf("%I64d", &n); i <= n; scanf("%I64d", &a[i++]))
    ;
  for (i = 1; i <= n; l[i] = r[i] = i, i++)
    ;
  for (i = 2; i <= n; i++) {
    long long num = i;
    while (num > 1 && a[num - 1] <= a[i]) num = l[num - 1];
    l[i] = num;
  }
  for (i = n - 1; i >= 1; i--) {
    long long num = i;
    while (num < n && a[num + 1] < a[i]) num = r[num + 1];
    r[i] = num;
  }
  for (i = 1; i <= n; ans += (i - l[i] + 1) * (r[i] - i + 1) * a[i], i++)
    ;
  for (i = 1; i <= n; l[i] = r[i] = i, i++)
    ;
  for (i = 2; i <= n; i++) {
    long long num = i;
    while (num > 1 && a[num - 1] >= a[i]) num = l[num - 1];
    l[i] = num;
  }
  for (i = n - 1; i >= 1; i--) {
    long long num = i;
    while (num < n && a[num + 1] > a[i]) num = r[num + 1];
    r[i] = num;
  }
  for (i = 1; i <= n; i++) {
    ans -= (i - l[i] + 1) * (r[i] - i + 1) * a[i];
  }
  printf("%I64d\n", ans);
}
