#include <bits/stdc++.h>
using namespace std;
vector<long long> prevSmall(vector<long long> &a, long long n) {
  vector<long long> res(n, -1);
  for (long long i = 1; i < n; ++i) {
    long long j = i - 1;
    while (j >= 0 && a[j] >= a[i]) j = res[j];
    res[i] = j;
  }
  return res;
}
vector<long long> nextSmall(vector<long long> &a, long long n) {
  vector<long long> res(n, n);
  for (long long i = n - 2; i >= 0; --i) {
    long long j = i + 1;
    while (j < n && a[j] > a[i]) j = res[j];
    res[i] = j;
  }
  return res;
}
vector<long long> prevLarge(vector<long long> &a, long long n) {
  vector<long long> res(n, -1);
  for (long long i = 1; i < n; ++i) {
    long long j = i - 1;
    while (j >= 0 && a[j] <= a[i]) j = res[j];
    res[i] = j;
  }
  return res;
}
vector<long long> nextLarge(vector<long long> &a, long long n) {
  vector<long long> res(n, n);
  for (long long i = n - 2; i >= 0; --i) {
    long long j = i + 1;
    while (j < n && a[j] < a[i]) j = res[j];
    res[i] = j;
  }
  return res;
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  {
    long long n;
    cin >> n;
    vector<long long> a(n);
    for (long long i = 0; i < (n); ++i) cin >> a[i];
    long long ans = 0;
    auto pl = prevLarge(a, n), ps = prevSmall(a, n);
    auto nl = nextLarge(a, n), ns = nextSmall(a, n);
    for (long long i = 0; i < (n); ++i) {
      long long lc = i - pl[i], rc = nl[i] - i;
      ;
      ans += lc * rc * a[i];
      lc = i - ps[i], rc = ns[i] - i;
      ;
      ans -= lc * rc * a[i];
    }
    cout << ans;
  }
  return 0;
}
