#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
int main() {
  iostream::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int n;
  cin >> n;
  vector<int> a(n), mxl = a, mxr = a, mnl = a, mnr = a;
  for (int i = 0; i < n; i++) cin >> a[i];
  stack<int> mn, mx;
  for (int i = 0; i < n; i++) {
    while (mn.size() && a[mn.top()] > a[i]) mn.pop();
    mnl[i] = (mn.size() ? mn.top() : -1);
    mn.push(i);
    while (mx.size() && a[mx.top()] < a[i]) mx.pop();
    mxl[i] = (mx.size() ? mx.top() : -1);
    mx.push(i);
  }
  while (mn.size()) mn.pop();
  while (mx.size()) mx.pop();
  for (int i = n - 1; i >= 0; i--) {
    while (mn.size() && a[mn.top()] >= a[i]) mn.pop();
    mnr[i] = (mn.size() ? mn.top() : n);
    mn.push(i);
    while (mx.size() && a[mx.top()] <= a[i]) mx.pop();
    mxr[i] = (mx.size() ? mx.top() : n);
    mx.push(i);
  }
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    long long dl = i - mnl[i], dr = mnr[i] - i;
    ans -= dl * dr * a[i];
    dl = i - mxl[i], dr = mxr[i] - i;
    ans += dl * dr * a[i];
  }
  cout << ans;
  return 0;
}
