#include <bits/stdc++.h>
using namespace std;
int n, a[1000010], pre[1000010][21], suf[1000010][21];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  a[0] = 0x3f3f3f3f;
  a[n + 1] = 0x3f3f3f3f;
  for (int i = 1; i <= n; i++) {
    pre[i][0] = a[i - 1];
    suf[i][0] = a[i + 1];
  }
  for (int i = 1; i <= 20; i++) {
    for (int j = 1; j <= n; j++) {
      pre[j][i] = max(pre[j][i - 1], pre[max(0, j - (1 << i - 1))][i - 1]);
      suf[j][i] = max(suf[j][i - 1], suf[min(n + 1, j + (1 << i - 1))][i - 1]);
    }
  }
  long long ans1 = 0;
  for (int i = 1; i <= n; i++) {
    int l = i, r = i;
    for (int j = 20; j >= 0; j--) {
      if (pre[l][j] < a[i]) {
        l -= (1 << j);
      }
    }
    for (int j = 20; j >= 0; j--) {
      if (suf[r][j] <= a[i]) {
        r += (1 << j);
      }
    }
    ans1 += 1ll * a[i] * (i - l + 1) * (r - i + 1);
  }
  a[0] = -0x3f3f3f3f;
  a[n + 1] = -0x3f3f3f3f;
  for (int i = 1; i <= n; i++) {
    pre[i][0] = a[i - 1];
    suf[i][0] = a[i + 1];
  }
  for (int i = 1; i <= 20; i++) {
    for (int j = 1; j <= n; j++) {
      pre[j][i] = min(pre[j][i - 1], pre[max(0, j - (1 << i - 1))][i - 1]);
      suf[j][i] = min(suf[j][i - 1], suf[min(n + 1, j + (1 << i - 1))][i - 1]);
    }
  }
  long long ans2 = 0;
  for (int i = 1; i <= n; i++) {
    int l = i, r = i;
    for (int j = 20; j >= 0; j--) {
      if (pre[l][j] > a[i]) {
        l -= (1 << j);
      }
    }
    for (int j = 20; j >= 0; j--) {
      if (suf[r][j] >= a[i]) {
        r += (1 << j);
      }
    }
    ans2 += 1ll * a[i] * (i - l + 1) * (r - i + 1);
  }
  printf("%lld\n", ans1 - ans2);
  return 0;
}
