#include <bits/stdc++.h>
using namespace std;
const int N = 1255001;
const int SQRTN = 320;
const int LOGN = 20;
const long double PI = acos(-1);
const long double TAU = 2 * PI;
int n, a[N], nxt[2][N], prv[2][N];
stack<int> st[2];
signed main() {
  cin >> n;
  for (int i = 0; i < n; i++) scanf("%d", a + i);
  for (int i = 0; i < n; i++) {
    while (!st[0].empty()) {
      if (a[st[0].top()] >= a[i]) break;
      st[0].pop();
    }
    if (st[0].empty())
      prv[0][i] = -1;
    else
      prv[0][i] = st[0].top();
    while (!st[1].empty()) {
      if (a[st[1].top()] <= a[i]) break;
      st[1].pop();
    }
    if (st[1].empty())
      prv[1][i] = -1;
    else
      prv[1][i] = st[1].top();
    st[0].push(i);
    st[1].push(i);
  }
  while (!st[0].empty()) st[0].pop();
  while (!st[1].empty()) st[1].pop();
  for (int i = n - 1; i >= 0; i--) {
    while (!st[0].empty()) {
      if (a[st[0].top()] > a[i]) break;
      st[0].pop();
    }
    if (st[0].empty())
      nxt[0][i] = n;
    else
      nxt[0][i] = st[0].top();
    while (!st[1].empty()) {
      if (a[st[1].top()] < a[i]) break;
      st[1].pop();
    }
    if (st[1].empty())
      nxt[1][i] = n;
    else
      nxt[1][i] = st[1].top();
    st[0].push(i);
    st[1].push(i);
  }
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    ans = ans + (1ll * a[i] * (nxt[0][i] - i) * (i - prv[0][i]));
    ans = ans - (1ll * a[i] * (nxt[1][i] - i) * (i - prv[1][i]));
  }
  cout << ans << endl;
}
