#include <bits/stdc++.h>
using namespace std;
constexpr int N = 1e6 + 9;
int n, a[N];
int stk[N];
void get(int* sve, bool tag = false) {
  stk[stk[0] = 1] = 0;
  for (int i = 1; i <= n; ++i) {
    while (tag ? a[i] >= a[stk[stk[0]]] : a[i] > a[stk[stk[0]]]) --stk[0];
    sve[i] = stk[stk[0]];
    stk[++stk[0]] = i;
  }
}
int s1[N], s2[N], s3[N], s4[N];
int main() {
  cin >> n, a[0] = INT_MAX;
  for (int i = 1; i <= n; ++i) cin >> a[i];
  get(s1);
  reverse(a + 1, a + n + 1);
  get(s2, true);
  for (int i = 1; i <= n; ++i) s2[i] = n + 1 - s2[i], a[i] = -a[i];
  reverse(s2 + 1, s2 + n + 1);
  get(s4, true);
  for (int i = 1; i <= n; ++i) s4[i] = n + 1 - s4[i];
  reverse(s4 + 1, s4 + n + 1);
  reverse(a + 1, a + n + 1);
  get(s3);
  for (int i = 1; i <= n; ++i) a[i] = -a[i];
  long long ret = 0;
  for (int i = 1; i <= n; ++i) {
    ret += 1ll * a[i] * (i - s1[i]) * (s2[i] - i);
    ret -= 1ll * a[i] * (i - s3[i]) * (s4[i] - i);
  }
  cout << ret << endl;
  return 0;
}
