#include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
  if (0) return;
  cout << name << " : " << arg1 << '\n';
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
  if (0) return;
  const char* comma = strchr(names + 1, ',');
  cout.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
inline void INP();
const int N = 1e6 + 7, M = 1000000007, inf = INT_MAX;
const long long INF = LLONG_MAX;
int n, Q;
int arr[N + 2], lgg[N + 2];
pair<int, int> table[N + 2][21];
void compute() {
  lgg[1] = 0;
  for (int i = 2; i < (int)N; i++) lgg[i] = lgg[i / 2] + 1;
  for (int i = 1; i < (int)n + 1; i++)
    table[i][0].first = table[i][0].second = arr[i];
  for (int j = 1; j < (int)21; j++) {
    for (int i = 1; i < (int)n + 1; i++) {
      if (i + (1 << (j - 1)) >= N) continue;
      table[i][j].first =
          max(table[i][j - 1].first, table[i + (1 << (j - 1))][j - 1].first);
      table[i][j].second =
          min(table[i][j - 1].second, table[i + (1 << (j - 1))][j - 1].second);
    }
  }
}
int getmax(int l, int r) {
  int p = lgg[r - l + 1];
  int res = max(table[l][p].first, table[r - (1 << p) + 1][p].first);
  return res;
}
int getmin(int l, int r) {
  int p = lgg[r - l + 1];
  int res = min(table[l][p].second, table[r - (1 << p) + 1][p].second);
  return res;
}
pair<long long, long long> dp[N];
void solve() {
  cin >> n;
  for (int i = 1; i < (int)n + 1; i++) cin >> arr[i];
  compute();
  for (int i = 1; i < (int)n + 1; i++) {
    int s = 1, e = i - 1, res = i;
    while (s <= e) {
      int mid = (s + e) / 2;
      if (getmax(mid, i) > arr[i])
        s = ++mid;
      else {
        res = mid;
        e = --mid;
      }
    }
    dp[i].first = dp[res - 1].first + (1LL * arr[i] * (i - res + 1));
  }
  for (int i = 1; i < (int)n + 1; i++) {
    int s = 1, e = i - 1, res = i;
    while (s <= e) {
      int mid = (s + e) / 2;
      if (getmin(mid, i) < arr[i])
        s = ++mid;
      else {
        res = mid;
        e = --mid;
      }
    }
    dp[i].second = dp[res - 1].second + (1LL * arr[i] * (i - res + 1));
  }
  long long ans = 0;
  for (int i = 1; i < (int)n + 1; i++) ans += (dp[i].first - dp[i].second);
  cout << ans << '\n';
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  INP();
  int t = 1;
  while (t--) solve();
}
inline void INP() {}
