#include <bits/stdc++.h>
using namespace std;
const long long UNDEF = -1;
const int INF = 1 << 25;
template <typename T>
inline bool chkmax(T& aa, T bb) {
  return aa < bb ? aa = bb, true : false;
}
template <typename T>
inline bool chkmin(T& aa, T bb) {
  return aa > bb ? aa = bb, true : false;
}
static char stdinBuffer[1024];
static char* stdinDataEnd = stdinBuffer + sizeof(stdinBuffer);
static const char* stdinPos = stdinDataEnd;
void readAhead(size_t amount) {
  size_t remaining = stdinDataEnd - stdinPos;
  if (remaining < amount) {
    memmove(stdinBuffer, stdinPos, remaining);
    size_t sz = fread(stdinBuffer + remaining, 1,
                      sizeof(stdinBuffer) - remaining, stdin);
    stdinPos = stdinBuffer;
    stdinDataEnd = stdinBuffer + remaining + sz;
    if (stdinDataEnd != stdinBuffer + sizeof(stdinBuffer)) *stdinDataEnd = 0;
  }
}
int readInt() {
  readAhead(16);
  int x = 0;
  bool neg = false;
  while (*stdinPos == ' ' || *stdinPos == '\n') ++stdinPos;
  if (*stdinPos == '-') {
    ++stdinPos;
    neg = true;
  }
  while (*stdinPos >= '0' && *stdinPos <= '9') {
    x *= 10;
    x += *stdinPos - '0';
    ++stdinPos;
  }
  return neg ? -x : x;
}
char readCh() {
  readAhead(16);
  while (*stdinPos == ' ' || *stdinPos == '\n') ++stdinPos;
  char ans = *stdinPos;
  ++stdinPos;
  return ans;
}
const int mn = 1000000;
pair<int, int> vp[mn];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n = readInt();
  for (int i = 0; i < n; i++) {
    int val = readInt();
    vp[i] = make_pair(val, i);
  }
  sort(vp, vp + n);
  long long final = 0;
  long long sign = -1;
  for (int k = 0; k < 2; k++) {
    set<int> s;
    s.insert(-1);
    s.insert(n);
    for (int i = 0; i < n; i++) {
      int x = vp[i].second;
      auto got = s.insert(x);
      auto it = got.first;
      auto lit = it;
      --lit;
      auto rit = it;
      ++rit;
      long long l = x - *lit;
      long long r = *rit - x;
      long long prod = l * r;
      long long val = (long long)vp[i].first * (long long)prod * sign;
      final += val;
    }
    reverse(vp, vp + n);
    sign = -sign;
  }
  printf("%lld\n", final);
}
