#include <bits/stdc++.h>
using namespace std;
const long long int inf = (long long int)1e18 + 10;
stack<pair<long long int, long long int> > s, r;
long long int lm[1000056], rm[1000056], ls[1000056], rs[1000056];
long long int a[1000056];
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int n, sumax = 0, sumin = 0;
  cin >> n;
  for (long long int i = 1; i <= n; i++) {
    cin >> a[i];
    while (s.size() > 0) {
      pair<long long int, long long int> x = s.top();
      if (a[i] > x.first) {
        rs[x.second] = i;
        s.pop();
      } else
        break;
    }
    s.push(make_pair(a[i], i));
    while (r.size() > 0) {
      pair<long long int, long long int> x = r.top();
      if (a[i] < x.first) {
        rm[x.second] = i;
        r.pop();
      } else
        break;
    }
    r.push(make_pair(a[i], i));
  }
  while (s.size() > 0) {
    pair<long long int, long long int> x = s.top();
    rs[x.second] = n + 1;
    s.pop();
  }
  while (r.size() > 0) {
    pair<long long int, long long int> x = r.top();
    rm[x.second] = n + 1;
    r.pop();
  }
  for (long long int i = n; i >= 1; i--) {
    while (s.size() > 0) {
      pair<long long int, long long int> x = s.top();
      if (a[i] >= x.first) {
        ls[x.second] = i;
        s.pop();
      } else
        break;
    }
    s.push(make_pair(a[i], i));
    while (r.size() > 0) {
      pair<long long int, long long int> x = r.top();
      if (a[i] <= x.first) {
        lm[x.second] = i;
        r.pop();
      } else
        break;
    }
    r.push(make_pair(a[i], i));
  }
  while (s.size() > 0) {
    pair<long long int, long long int> x = s.top();
    ls[x.second] = 0;
    s.pop();
  }
  while (r.size() > 0) {
    pair<long long int, long long int> x = r.top();
    lm[x.second] = 0;
    r.pop();
  }
  for (long long int i = 1; i <= n; i++) {
    sumax += a[i] * (rs[i] - i) * (i - ls[i]);
    sumin += a[i] * (rm[i] - i) * (i - lm[i]);
  }
  cout << (sumax - sumin) << "\n";
}
