#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int n, a[N], k = 23, mnRt[N], mnLf[N], mxRt[N], mxLf[N];
stack<int> sk;
vector<int> v[1000005];
long long ansMn, ansMx;
void solve(int ii) {
  long long l = -1, lst = -1, r, idx;
  for (int i = 0; i < v[ii].size(); i++) {
    idx = v[ii][i];
    l = max(lst + 1, (long long)mnLf[idx] + 1);
    r = mnRt[idx] - 1;
    lst = idx;
    ansMn += (idx - l + 1) * (r - idx + 1) * a[idx];
  }
  l = -1, lst = -1;
  for (int i = 0; i < v[ii].size(); i++) {
    idx = v[ii][i];
    l = max(lst + 1, (long long)mxLf[idx] + 1);
    r = mxRt[idx] - 1;
    lst = idx;
    ansMx += (idx - l + 1) * (r - idx + 1) * a[idx];
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    mnLf[i] = -1, mxLf[i] = -1, mnRt[i] = n, mxRt[i] = n;
    while (sk.size() && a[sk.top()] >= a[i]) sk.pop();
    if (sk.size()) mnLf[i] = sk.top();
    v[a[i]].push_back(i);
    sk.push(i);
  }
  while (sk.size()) sk.pop();
  for (int i = 0; i < n; i++) {
    while (sk.size() && a[sk.top()] <= a[i]) sk.pop();
    if (sk.size()) mxLf[i] = sk.top();
    sk.push(i);
  }
  while (sk.size()) sk.pop();
  for (int i = n - 1; i >= 0; i--) {
    while (sk.size() && a[sk.top()] >= a[i]) sk.pop();
    if (sk.size()) mnRt[i] = sk.top();
    sk.push(i);
  }
  while (sk.size()) sk.pop();
  for (int i = n - 1; i >= 0; i--) {
    while (sk.size() && a[sk.top()] <= a[i]) sk.pop();
    if (sk.size()) mxRt[i] = sk.top();
    sk.push(i);
  }
  for (int i = 1; i <= 1000000; i++) {
    if (v[i].size()) {
      solve(i);
    }
  }
  printf("%lld\n", ansMx - ansMn);
  return 0;
}
