#include <bits/stdc++.h>
const int N = 1e6 + 1;
long long s;
int i, n, a[N], l[N], r[N];
void wk() {
  for (i = n; i; --i)
    for (r[i] = i + 1; r[i] <= n && a[i] > a[r[i]]; r[i] = r[r[i]])
      ;
  for (i = 0; i++ < n; s += 1ll * (i - l[i]) * (r[i] - i) * a[i])
    for (l[i] = i - 1; l[i] && a[i] >= a[l[i]]; l[i] = l[l[i]])
      ;
}
int main() {
  for (scanf("%d", &n); i++ < n; scanf("%d", a + i))
    ;
  for (wk(), i = 0; i++ < n; a[i] = -a[i])
    ;
  wk(), printf("%lld", s);
}
