#include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& p) {
  os << "[ ";
  for (T x : p) os << x << " ";
  os << "]" << endl;
  return os;
}
template <typename T>
ostream& operator<<(ostream& os, const set<T>& p) {
  os << "{ ";
  for (T x : p) os << x << " ";
  os << "}" << endl;
  return os;
}
template <typename Tk, typename Tv>
ostream& operator<<(ostream& os, const map<Tk, Tv>& p) {
  os << "{ ";
  for (pair<Tk, Tv> x : p) os << x << " ";
  os << "}" << endl;
  return os;
}
template <typename Tk, typename Tv>
ostream& operator<<(ostream& os, const pair<Tk, Tv>& p) {
  os << "{" << p.first << ',' << p.second << "}";
  return os;
}
const int MOD = 1000000000 + 7;
const int INF = 1000000000 + 5;
const int MAX = 1000005;
int after[MAX], before[MAX];
int main() {
  long long ranges = 0;
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  vector<long long> a(n);
  for (int i = 0; i < n; i++) cin >> a[i];
  long long sum = 0;
  {
    stack<pair<int, int> > S, T;
    for (int i = 0; i < n; i++) {
      while (!S.empty() && (S.top().first < a[i])) S.pop();
      if (S.empty()) {
        before[i] = -1;
      } else {
        before[i] = S.top().second;
      }
      S.push(make_pair(a[i], i));
    }
    for (int i = n - 1; i >= 0; i--) {
      while (!T.empty() && (T.top().first <= a[i])) T.pop();
      if (T.empty()) {
        after[i] = n;
      } else {
        after[i] = T.top().second;
      }
      T.push(make_pair(a[i], i));
    }
    for (int i = 0; i < n; i++) {
      sum += (long long)(i - before[i]) * (after[i] - i) * a[i];
      ranges += (long long)(i - before[i]) * (after[i] - i);
    }
  }
  {
    ranges = 0;
    memset(before, 0, sizeof(before));
    memset(after, 0, sizeof(after));
    stack<pair<int, int> > S, T;
    for (int i = 0; i < n; i++) {
      while (!S.empty() && (S.top().first > a[i])) S.pop();
      if (S.empty()) {
        before[i] = -1;
      } else {
        before[i] = S.top().second;
      }
      S.push(make_pair(a[i], i));
    }
    for (int i = n - 1; i >= 0; i--) {
      while (!T.empty() && (T.top().first >= a[i])) T.pop();
      if (T.empty()) {
        after[i] = n;
      } else {
        after[i] = T.top().second;
      }
      T.push(make_pair(a[i], i));
    }
    for (int i = 0; i < n; i++) {
      sum -= (long long)(i - before[i]) * (after[i] - i) * a[i];
      ranges += (long long)(i - before[i]) * (after[i] - i);
    }
  }
  cout << sum << endl;
}
