#include <bits/stdc++.h>
using namespace std;
const double pi = 3.141592653589793;
const int SZ = 1000005, mod = 1000000007;
long long n;
long long ara[SZ];
stack<pair<long long, long long> > mn, mx;
long long sumn, sumx;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> ara[i];
  }
  long long ans = 0;
  sumn = ara[0];
  sumx = ara[0];
  mn.push(make_pair(sumn, sumn));
  mx.push(make_pair(sumn, sumx));
  for (int i = 1; i < n; i++) {
    long long x = ara[i], s = x;
    while (!mn.empty() && mn.top().first >= x) {
      sumn -= mn.top().second;
      s += x * (mn.top().second / mn.top().first);
      mn.pop();
    }
    sumn += s;
    mn.push(make_pair(x, s));
    x = ara[i], s = x;
    while (!mx.empty() && mx.top().first <= x) {
      sumx -= mx.top().second;
      s += x * (mx.top().second / mx.top().first);
      mx.pop();
    }
    sumx += s;
    mx.push(make_pair(x, s));
    ans += (sumx - sumn);
  }
  cout << ans << endl;
  return 0;
}
