#include <bits/stdc++.h>
using namespace std;
int A[1000010], stk[1000010], Top, L[1000010];
int main() {
  int n, i;
  long long Ans = 0;
  scanf("%d", &n);
  for (i = 1; i <= n; i++) {
    scanf("%d", &A[i]);
  }
  Top = 0;
  stk[0] = 0;
  for (i = 1; i <= n; i++) {
    while (Top > 0 && A[stk[Top]] > A[i]) {
      Top--;
    }
    L[i] = stk[Top] + 1;
    stk[++Top] = i;
  }
  Top = 0;
  stk[0] = n + 1;
  for (i = n; i >= 1; i--) {
    while (Top > 0 && A[stk[Top]] >= A[i]) {
      Top--;
    }
    Ans -= 1LL * A[i] * (i - L[i] + 1) * (stk[Top] - i);
    stk[++Top] = i;
  }
  Top = 0;
  stk[0] = 0;
  for (i = 1; i <= n; i++) {
    while (Top > 0 && A[stk[Top]] < A[i]) {
      Top--;
    }
    L[i] = stk[Top] + 1;
    stk[++Top] = i;
  }
  Top = 0;
  stk[0] = n + 1;
  for (i = n; i >= 1; i--) {
    while (Top > 0 && A[stk[Top]] <= A[i]) {
      Top--;
    }
    Ans += 1LL * A[i] * (i - L[i] + 1) * (stk[Top] - i);
    stk[++Top] = i;
  }
  printf("%lld\n", Ans);
  return 0;
}
