#include <bits/stdc++.h>
template <class _, class __>
bool checkmax(_ &a, __ b) {
  return a < b ? a = b, true : false;
}
template <class _, class __>
bool checkmin(_ &a, __ b) {
  return a > b ? a = b, true : false;
}
using namespace std;
int n;
int A[1000086];
int L[1000086], R[1000086];
int main() {
  cin >> n;
  for (int i = (1), i_end_ = (n); i <= i_end_; ++i) scanf("%d", &A[i]);
  for (int i = (1), i_end_ = (n); i <= i_end_; ++i) L[i] = R[i] = i;
  for (int i = (2), i_end_ = (n); i <= i_end_; ++i) {
    int cur = i;
    while (cur > 1 && A[i] >= A[cur - 1]) cur = L[cur - 1];
    L[i] = cur;
  }
  for (int i = (n - 1), i_end_ = (1); i >= i_end_; --i) {
    int cur = i;
    while (cur < n && A[i] > A[cur + 1]) cur = R[cur + 1];
    R[i] = cur;
  }
  long long ans = 0;
  for (int i = (1), i_end_ = (n); i <= i_end_; ++i)
    ans += 1ll * (i - L[i] + 1) * (R[i] - i + 1) * A[i];
  for (int i = (1), i_end_ = (n); i <= i_end_; ++i) L[i] = R[i] = i;
  for (int i = (2), i_end_ = (n); i <= i_end_; ++i) {
    int cur = i;
    while (cur > 1 && A[i] <= A[cur - 1]) cur = L[cur - 1];
    L[i] = cur;
  }
  for (int i = (n - 1), i_end_ = (1); i >= i_end_; --i) {
    int cur = i;
    while (cur < n && A[i] < A[cur + 1]) cur = R[cur + 1];
    R[i] = cur;
  }
  for (int i = (1), i_end_ = (n); i <= i_end_; ++i)
    ans -= 1ll * (i - L[i] + 1) * (R[i] - i + 1) * A[i];
  printf("%I64d\n", ans);
  return EXIT_SUCCESS;
}
