#include <bits/stdc++.h>
using namespace std;
struct number {
  long long num, id, rec;
} a[1000001];
bool cmp(number a, number b) { return a.num < b.num; }
long long n, fa[1000002], s[1000002], ans;
int get_fa(long long t) {
  return t == fa[t] || fa[t] == 0 ? fa[t] : fa[t] = get_fa(fa[t]);
}
void process(int t) {
  int i, j;
  if (t == 1)
    i = 1, j = n + 1;
  else
    i = n, j = 0;
  for (; i != j; i += t) {
    fa[a[i].id] = a[i].id;
    s[a[i].id] = 1;
    long long p = get_fa(a[i].id - 1), q = get_fa(a[i].id + 1);
    a[i].rec = (s[p] + 1) * (s[q] + 1);
    if (s[p]) {
      s[p] += s[get_fa(a[i].id)];
      fa[get_fa(a[i].id)] = p;
    }
    if (s[q]) {
      s[q] += s[get_fa(a[i].id)];
      fa[get_fa(a[i].id)] = q;
    }
  }
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i].num;
    a[i].id = i;
  }
  sort(a + 1, a + n + 1, cmp);
  process(1);
  for (int i = 1; i <= n; ++i) {
    ans += a[i].num * a[i].rec;
  }
  memset(fa, 0, sizeof(fa));
  memset(s, 0, sizeof(s));
  process(-1);
  for (int i = 1; i <= n; ++i) {
    ans -= a[i].num * a[i].rec;
  }
  cout << ans << endl;
  return 0;
}
