#include <bits/stdc++.h>
using namespace std;
int n;
pair<int, int> a[1000005];
int l[1000005];
int r[1000005];
bool v[1000005];
long long int res;
void f(int i, int M) {
  int c = a[i].second;
  long long int X = a[i].first;
  l[c] = c;
  r[c] = c;
  v[c] = true;
  if (c > 0 && v[c - 1]) l[c] = l[c - 1];
  if (c < n - 1 && v[c + 1]) r[c] = r[c + 1];
  long long int L = c - l[c] + 1;
  long long int R = r[c] - c + 1;
  res += X * R * L * M;
  r[l[c]] = r[c];
  l[r[c]] = l[c];
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i].first;
    a[i].second = i;
  }
  sort(a, a + n);
  for (int i = n - 1; i >= 0; i--) f(i, -1);
  memset(v, false, sizeof(v));
  for (int i = 0; i < n; i++) f(i, +1);
  cout << res;
  return 0;
}
