#include <bits/stdc++.h>
using namespace std;
const int N = 1000001;
int n, v[N], l[N], r[N];
vector<int> at[N];
int mx[N];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &v[i]);
  long long res = 0;
  for (int it = 0; it < 2; ++it) {
    for (int i = 0; i < N; ++i) at[i].clear();
    for (int i = 1; i <= n; ++i) {
      at[v[i]].push_back(i);
      if (it) v[i] *= -1;
    }
    stack<int> s;
    for (int i = 1; i <= n; ++i) {
      while (!s.empty() && v[s.top()] >= v[i]) s.pop();
      l[i] = s.empty() ? 0 : s.top();
      s.push(i);
    }
    s = stack<int>();
    for (int i = n; i > 0; --i) {
      while (!s.empty() && v[s.top()] >= v[i]) s.pop();
      r[i] = s.empty() ? n + 1 : s.top();
      s.push(i);
    }
    for (int i = 1; i <= n; ++i) {
      int val = abs(v[i]);
      int from = l[i] + 1;
      int to = r[i] - 1;
      int a = upper_bound(at[val].begin(), at[val].end(), i) - at[val].begin();
      if (a != at[val].size()) to = min(to, at[val][a] - 1);
      res -= v[i] * (long long)(i - from + 1) * (to - i + 1);
    }
  }
  cout << res << endl;
  return 0;
}
