#include <bits/stdc++.h>
using namespace std;
const long long N = 1e6 + 5;
long long l[N], r[N];
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  long long arr[n];
  for (auto &x : arr) cin >> x;
  iota(l, l + N, 0);
  iota(r, r + N, 0);
  for (long long i = 1; i < n; i++) {
    long long pos = i;
    while (pos && arr[pos - 1] <= arr[i]) pos = r[pos - 1];
    r[i] = pos;
  }
  for (long long i = n - 2; ~i; i--) {
    long long pos = i;
    while (pos < n - 1 && arr[i] > arr[pos + 1]) pos = l[pos + 1];
    l[i] = pos;
  }
  long long ans = 0;
  for (long long i = 0; i < n; i++)
    ans += (i - r[i] + 1) * (l[i] - i + 1) * arr[i];
  iota(l, l + N, 0);
  iota(r, r + N, 0);
  for (long long i = 1; i < n; i++) {
    long long pos = i;
    while (pos && arr[pos - 1] >= arr[i]) pos = r[pos - 1];
    r[i] = pos;
  }
  for (long long i = n - 2; ~i; i--) {
    long long pos = i;
    while (pos < n - 1 && arr[i] < arr[pos + 1]) pos = l[pos + 1];
    l[i] = pos;
  }
  for (long long i = 0; i < n; i++)
    ans -= (i - r[i] + 1) * (l[i] - i + 1) * arr[i];
  cout << ans << "\n";
}
