#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1e6 + 5;
stack<long long> q;
stack<pair<int, int> > s1, s2;
long long haha[MAXN], sth[MAXN];
long long n;
long long a[MAXN];
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 1; i <= n; i++) {
    while (q.size() != 0 && a[q.top()] <= a[i]) {
      haha[i] += haha[q.top()] + 1;
      q.pop();
    }
    q.push(i);
  }
  while (q.size() != 0) q.pop();
  for (int i = n; i >= 1; i--) {
    while (q.size() != 0 && a[q.top()] < a[i]) {
      sth[i] += sth[q.top()] + 1;
      q.pop();
    }
    q.push(i);
  }
  while (q.size() != 0) q.pop();
  long long ans = 0;
  for (int i = 1; i <= n; i++) ans += (haha[i] + 1) * (sth[i] + 1) * a[i];
  memset(haha, 0, sizeof(haha));
  memset(sth, 0, sizeof(sth));
  for (int i = 1; i <= n; ++i) {
    int cnt = 1;
    while (!s1.empty() && (s1.top().first) > a[i]) {
      cnt += s1.top().second;
      s1.pop();
    }
    s1.push({a[i], cnt});
    haha[i] = cnt;
  }
  for (int i = n; i >= 1; --i) {
    int cnt = 1;
    while (!s2.empty() && (s2.top().first) >= a[i]) {
      cnt += s2.top().second;
      s2.pop();
    }
    s2.push({a[i], cnt});
    sth[i] = cnt;
  }
  long long result = 0;
  for (int i = 1; i <= n; ++i) result = (result + a[i] * haha[i] * sth[i]);
  cout << abs(ans - result);
}
