#include <bits/stdc++.h>
using namespace std;
inline void Rd(int &res) {
  char c;
  res = 0;
  while (c = getchar(), c < '0')
    ;
  do {
    res = (res << 1) + (res << 3) + (c ^ 48);
  } while (c = getchar(), c >= '0');
}
const int M = (int)1e6 + 5;
int n;
long long ans;
int L[M], R[M];
struct Node {
  int id, v;
  bool operator<(const Node &A) const { return v < A.v; }
} A[M];
int findL(int x) {
  if (L[x] == x)
    return x;
  else
    return L[x] = findL(L[x]);
}
int findR(int x) {
  if (R[x] == x)
    return x;
  else
    return R[x] = findR(R[x]);
}
int main() {
  Rd(n);
  for (int i = 1; i <= n; i++) Rd(A[i].v), A[i].id = i;
  sort(A + 1, A + n + 1);
  for (int i = 0; i <= n + 1; i++) L[i] = i, R[i] = i;
  for (int i = 1; i <= n; i++) {
    int l = findL(A[i].id - 1), r = findR(A[i].id + 1);
    ans += (long long)A[i].v * (A[i].id - l) * (r - A[i].id);
    L[A[i].id] = A[i].id - 1, R[A[i].id] = A[i].id + 1;
  }
  for (int i = 0; i <= n + 1; i++) L[i] = i, R[i] = i;
  for (int i = n; i >= 1; i--) {
    int l = findL(A[i].id - 1), r = findR(A[i].id + 1);
    ans -= (long long)A[i].v * (A[i].id - l) * (r - A[i].id);
    L[A[i].id] = A[i].id - 1, R[A[i].id] = A[i].id + 1;
  }
  cout << ans << endl;
  return 0;
}
