#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 20;
int arr[N], lastMin[N], lastMax[N];
long long int Min[N], Max[N];
int main() {
  int n;
  long long int ans = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
  memset(lastMin, -1, sizeof lastMin);
  memset(lastMax, -1, sizeof lastMax);
  stack<pair<int, int> > st;
  for (int i = 0; i < n; i++) {
    int cur = arr[i];
    while (st.size() && st.top().first >= cur) st.pop();
    if (st.size()) lastMin[i] = st.top().second;
    st.push(make_pair(arr[i], i));
  }
  while (st.size()) st.pop();
  for (int i = 0; i < n; i++) {
    int cur = arr[i];
    while (st.size() && st.top().first <= cur) st.pop();
    if (st.size()) lastMax[i] = st.top().second;
    st.push(make_pair(arr[i], i));
  }
  for (int i = 0; i < n; i++) {
    if (lastMin[i] != -1)
      Min[i] = Min[lastMin[i]] + 1ll * (i - lastMin[i]) * arr[i];
    else
      Min[i] = 1ll * (i - lastMin[i]) * arr[i];
    if (lastMax[i] != -1)
      Max[i] = Max[lastMax[i]] + 1ll * (i - lastMax[i]) * arr[i];
    else
      Max[i] = 1ll * (i - lastMax[i]) * arr[i];
    ans += Max[i] - Min[i];
  }
  printf("%I64d\n", ans);
  return 0;
}
