#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
template <typename T, typename TT>
inline ostream &operator<<(ostream &os, const pair<T, TT> &t) {
  return os << t.first << " " << t.second;
}
template <typename T>
inline ostream &operator<<(ostream &os, const vector<T> &t) {
  for (auto i : t) os << i << " ";
  return os;
}
template <typename T>
inline ostream &operator<<(ostream &os, const set<T> &t) {
  for (auto i : t) os << i << " ";
  return os;
}
template <typename T1, typename T2>
inline ostream &operator<<(ostream &os, const map<T1, T2> &t) {
  for (auto i : t) os << i.first << " : " << i.second << '\n';
  return os;
}
template <typename T>
inline istream &operator>>(istream &is, vector<T> &v) {
  for (T &t : v) is >> t;
  return is;
}
template <typename T1, typename T2>
inline istream &operator>>(istream &is, vector<pair<T1, T2>> &v) {
  for (pair<T1, T2> &t : v) is >> t.first >> t.second;
  return is;
}
const long long mod = 1e9 + 7;
void solve() {
  long long n;
  cin >> n;
  vector<long long> v(n);
  cin >> v;
  vector<array<long long, 3>> smx, smn;
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    while (!smx.empty() and smx.back()[0] <= v[i]) smx.pop_back();
    if (smx.empty())
      smx.push_back({v[i], i, v[i] * (i + 1)});
    else
      smx.push_back({v[i], i, smx.back()[2] + v[i] * (i - smx.back()[1])});
    while (!smn.empty() and smn.back()[0] >= v[i]) smn.pop_back();
    if (smn.empty())
      smn.push_back({v[i], i, v[i] * (i + 1)});
    else
      smn.push_back({v[i], i, smn.back()[2] + v[i] * (i - smn.back()[1])});
    ans += smx.back()[2] - smn.back()[2];
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  ;
  long long T = 1;
  while (T--) {
    solve();
  }
  return 0;
}
