#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios::sync_with_stdio(false), cin.tie(nullptr);
  cout << fixed << setprecision(0);
  int64_t n, sum = 0;
  cin >> n;
  vector<int64_t> mins(n), maxs(n), cs(n), cb(n), a(n);
  for (int64_t i = 0; i < int64_t(n); ++i) cin >> a[i];
  mins[0] = maxs[0] = a[0], cb[0] = cs[0] = -1;
  for (int64_t i = 1, cur; i < n; sum += maxs[i] - mins[i], i++) {
    for (cur = i - 1, cb[i] = i - 1; cur >= 0 && a[cur] < a[i];
         cur = cb[cur], cb[i] = cur)
      ;
    for (cur = i - 1, cs[i] = i - 1; cur >= 0 && a[cur] > a[i];
         cur = cs[cur], cs[i] = cur)
      ;
    maxs[i] = cb[i] != -1 ? (i - cb[i]) * a[i] + maxs[cb[i]] : (i + 1) * a[i];
    mins[i] = cs[i] != -1 ? (i - cs[i]) * a[i] + mins[cs[i]] : (i + 1) * a[i];
  }
  cout << sum;
  return 0;
}
