#include <bits/stdc++.h>
using namespace std;
long long arr[1000005], mins[1000005], maxs[1000005];
int fs[1000005], fb[1000005];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%lld", arr + i);
  }
  stack<long long> s;
  s.push(n - 1);
  for (int i = n - 2; i >= 0; i--) {
    while (!s.empty() && arr[i] > arr[s.top()]) {
      fb[s.top()] = i;
      s.pop();
    }
    s.push(i);
  }
  while (!s.empty()) {
    fb[s.top()] = -1;
    s.pop();
  }
  s.push(n - 1);
  for (int i = n - 2; i >= 0; i--) {
    while (!s.empty() && arr[i] < arr[s.top()]) {
      fs[s.top()] = i;
      s.pop();
    }
    s.push(i);
  }
  while (!s.empty()) {
    fs[s.top()] = -1;
    s.pop();
  }
  mins[0] = maxs[0] = arr[0];
  long long ans = 0;
  for (int i = 1; i < n; i++) {
    if (arr[i] == arr[i - 1]) {
      mins[i] = mins[i - 1] + arr[i];
      maxs[i] = maxs[i - 1] + arr[i];
    } else if (arr[i] > arr[i - 1]) {
      mins[i] = mins[i - 1] + arr[i];
      maxs[i] = (i - fb[i]) * arr[i];
      if (fb[i] >= 0) maxs[i] += maxs[fb[i]];
    } else {
      maxs[i] = maxs[i - 1] + arr[i];
      mins[i] = (i - fs[i]) * arr[i];
      if (fs[i] >= 0) mins[i] += mins[fs[i]];
    }
    ans += maxs[i] - mins[i];
  }
  printf("%lld\n", ans);
  return 0;
}
