#include <bits/stdc++.h>
using namespace std;
inline void read(long long &tx) {
  long long x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  tx = x * f;
}
inline void write(long long x) {
  if (x < 0) putchar('-'), x = -x;
  if (x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}
inline void writeln(long long x) {
  write(x);
  puts("");
}
using namespace std;
long long ans;
long long n, a[5000001], r[5000001], l[5000001], num[5000001], q[5000001];
int main() {
  read(n);
  for (long long i = 1; i <= n; i++) read(a[i]);
  long long top = 0;
  for (long long i = 1; i <= n; i++) {
    while (top && a[i] > q[top]) r[num[top]] = i, top--;
    l[i] = num[top] + 1;
    q[++top] = a[i];
    num[top] = i;
  }
  for (long long i = 1; i <= top; i++) r[num[i]] = n + 1;
  for (long long i = 1; i <= n; i++)
    ans += ((i - l[i]) * (r[i] - i - 1) + (i - l[i]) + (r[i] - i - 1)) * a[i];
  top = 0;
  memset(l, 0, sizeof l);
  for (long long i = 1; i <= n; i++) {
    while (top && a[i] < q[top]) r[num[top]] = i, top--;
    l[i] = num[top] + 1;
    q[++top] = a[i];
    num[top] = i;
  }
  for (long long i = 1; i <= top; i++) r[num[i]] = n + 1;
  for (long long i = 1; i <= n; i++)
    ans -= ((i - l[i]) * (r[i] - i - 1) + (i - l[i]) + (r[i] - i - 1)) * a[i];
  writeln(ans);
}
