#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
long long a[N], maxL[N], maxR[N], minL[N], minR[N];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  stack<int> s;
  for (int i = 1; i <= n; i++) {
    while (!s.empty() && a[s.top()] < a[i]) s.pop();
    if (s.empty())
      maxL[i] = 0;
    else
      maxL[i] = s.top();
    s.push(i);
  }
  stack<int> t;
  for (int i = n; i >= 1; i--) {
    while (!t.empty() && a[t.top()] <= a[i]) t.pop();
    if (t.empty())
      maxR[i] = n + 1;
    else
      maxR[i] = t.top();
    t.push(i);
  }
  stack<int> c;
  for (int i = 1; i <= n; i++) {
    while (!c.empty() && a[c.top()] > a[i]) c.pop();
    if (c.empty())
      minL[i] = 0;
    else
      minL[i] = c.top();
    c.push(i);
  }
  stack<int> k;
  for (int i = n; i >= 1; i--) {
    while (!k.empty() && a[k.top()] >= a[i]) k.pop();
    if (k.empty())
      minR[i] = n + 1;
    else
      minR[i] = k.top();
    k.push(i);
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    maxR[i]--;
    minR[i]--;
    maxL[i]++;
    minL[i]++;
    long long q = i - minL[i];
    long long w = minR[i] - i;
    long long e = i - maxL[i];
    long long r = maxR[i] - i;
    ans += ((e + 1) * (r + 1) - 1) * a[i] - ((q + 1) * (w + 1) - 1) * a[i];
  }
  cout << ans;
  return 0;
}
