#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
const int MOD = 1e9 + 7;
const long long M = 1e18;
long long qpow(long long a, long long b, long long m) {
  long long ans = 1;
  while (b) {
    if (b & 1) ans = (ans * a) % m;
    b /= 2;
    a = (a * a) % m;
  }
  return ans;
}
vector<int> nexts, nextg, prevs, prevg, arr;
int n;
void nextsmaller() {
  stack<int> st;
  st.push(0);
  int i = 1;
  while (i < n) {
    if (!st.empty()) {
      if (arr[st.top()] < arr[i])
        st.push(i);
      else {
        while ((!st.empty()) && (arr[st.top()] > arr[i])) {
          nexts[st.top()] = i;
          st.pop();
        }
        st.push(i);
      }
    } else
      st.push(i);
    i++;
  }
}
void nextgreater() {
  stack<int> st;
  st.push(0);
  int i = 1;
  while (i < n) {
    if (!st.empty()) {
      if (arr[st.top()] > arr[i])
        st.push(i);
      else {
        while ((!st.empty()) && (arr[st.top()] < arr[i])) {
          nextg[st.top()] = i;
          st.pop();
        }
        st.push(i);
      }
    } else
      st.push(i);
    i++;
  }
}
void prevsmaller() {
  stack<int> st;
  st.push(n - 1);
  int i = n - 2;
  while (i >= 0) {
    if (!st.empty()) {
      if (arr[st.top()] < arr[i])
        st.push(i);
      else {
        while ((!st.empty()) && (arr[st.top()] >= arr[i])) {
          prevs[st.top()] = i;
          st.pop();
        }
        st.push(i);
      }
    } else
      st.push(i);
    i--;
  }
}
void prevgreater() {
  stack<int> st;
  st.push(n - 1);
  int i = n - 2;
  while (i >= 0) {
    if (!st.empty()) {
      if (arr[st.top()] > arr[i])
        st.push(i);
      else {
        while ((!st.empty()) && (arr[st.top()] <= arr[i])) {
          prevg[st.top()] = i;
          st.pop();
        }
        st.push(i);
      }
    } else
      st.push(i);
    i--;
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int t = 1;
  while (t--) {
    cin >> n;
    arr.resize(n);
    nextg.resize(n);
    nexts.resize(n);
    prevg.resize(n);
    prevs.resize(n);
    for (int i = 0; i < n; i++) {
      cin >> arr[i];
    }
    if (n == 1) {
      cout << 0;
      return 0;
    }
    nextgreater();
    nextsmaller();
    prevgreater();
    prevsmaller();
    for (int i = 0; i < n; i++) {
      if (arr[nexts[i]] == arr[i] && nexts[i] > 0) nexts[i] += 1;
      if (arr[nextg[i]] == arr[i] && nextg[i] > 0) nextg[i] += 1;
      if (prevg[i] == 0 && arr[0] < arr[i]) prevg[i] = -1;
      if (prevs[i] == 0 && arr[0] > arr[i]) prevs[i] = -1;
      if (nexts[i] == 0) nexts[i] = n;
      if (nextg[i] == 0) nextg[i] = n;
    }
    long long sum_min = 0, sum_max = 0;
    for (int i = 0; i < n; i++) {
      sum_min +=
          (long long)(max(nexts[i] - i, 1)) * (max(i - prevs[i], 1)) * arr[i];
      sum_max +=
          (long long)(max(nextg[i] - i, 1)) * (max(i - prevg[i], 1)) * arr[i];
    }
    cout << sum_max - sum_min;
    cout << "\n";
  }
}
