#include <bits/stdc++.h>
using namespace std;
const long long N = 1e6;
long long st[N + 10], top = 0, a[N + 10], n;
long long minl[N + 10], minr[N + 10], maxl[N + 10], maxr[N + 10];
void init() {
  st[top = 1] = 1;
  for (long long i = 2; i <= n; i++) {
    while (top && a[st[top]] > a[i]) minr[st[top--]] = i - 1;
    st[++top] = i;
  }
  while (top) minr[st[top--]] = n;
  st[top = 1] = 1;
  for (long long i = 2; i <= n; i++) {
    while (top && a[st[top]] < a[i]) maxr[st[top--]] = i - 1;
    st[++top] = i;
  }
  while (top) maxr[st[top--]] = n;
  st[top = 1] = n;
  for (long long i = n - 1; i; i--) {
    while (top && a[st[top]] >= a[i]) minl[st[top--]] = i + 1;
    st[++top] = i;
  }
  while (top) minl[st[top--]] = 1;
  st[top = 1] = n;
  for (long long i = n - 1; i; i--) {
    while (top && a[st[top]] <= a[i]) maxl[st[top--]] = i + 1;
    st[++top] = i;
  }
  while (top) maxl[st[top--]] = 1;
}
signed main() {
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]);
  init();
  long long ans = 0;
  for (long long i = 1; i <= n; i++) {
    ans += (i - maxl[i] + 1) * (maxr[i] - i + 1) * a[i];
    ans -= (i - minl[i] + 1) * (minr[i] - i + 1) * a[i];
  }
  printf("%lld", ans);
  return 0;
}
