#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7, Base = 998244353;
const long long N = 1e6 + 7;
const long long INF = 1LL * 1000 * 1000 * 1000 * 1000 * 1000 * 1000 + 7LL;
const double pie = acos(-1.0);
const double EPS = 1e-9;
long long n, x, sum, r[N], l[N];
vector<long long> v[N];
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long i = 1; i <= n; ++i)
    cin >> x, v[x].push_back(i), l[i] = i - 1, r[i] = i + 1;
  for (long long i = N - 2; i >= 1; --i)
    for (long long j = (long long)v[i].size() - 1; j > -1; --j)
      sum -= (v[i][j] - l[v[i][j]]) * (r[v[i][j]] - v[i][j]) * i,
          r[l[v[i][j]]] = r[v[i][j]], l[r[v[i][j]]] = l[v[i][j]];
  for (long long i = 1; i <= n; ++i) l[i] = i - 1, r[i] = i + 1;
  for (long long i = 1; i < N; ++i)
    for (long long j = (long long)v[i].size() - 1; j > -1; --j)
      sum += (v[i][j] - l[v[i][j]]) * (r[v[i][j]] - v[i][j]) * i,
          r[l[v[i][j]]] = r[v[i][j]], l[r[v[i][j]]] = l[v[i][j]];
  cout << sum << '\n';
  return 0;
}
