#include <bits/stdc++.h>
using namespace std;
long long int n, a[1000001], l[1000001], r[1000001], minSum, maxSum;
stack<int> stk1, stk2, stk3, stk4;
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
  }
  for (int i = 0; i < n; ++i) {
    while (!stk1.empty() && a[i] < a[stk1.top()]) {
      stk1.pop();
    }
    if (stk1.empty())
      l[i] = -1;
    else
      l[i] = stk1.top();
    stk1.push(i);
  }
  for (int i = n - 1; i >= 0; --i) {
    while (!stk2.empty() && a[i] <= a[stk2.top()]) {
      stk2.pop();
    }
    if (stk2.empty())
      r[i] = n;
    else
      r[i] = stk2.top();
    stk2.push(i);
  }
  for (int i = 0; i < n; ++i) {
    minSum += (i - l[i]) * (r[i] - i) * a[i];
  }
  for (int i = 0; i < n; ++i) {
    while (!stk3.empty() && a[i] > a[stk3.top()]) {
      stk3.pop();
    }
    if (stk3.empty())
      l[i] = -1;
    else
      l[i] = stk3.top();
    stk3.push(i);
  }
  for (int i = n - 1; i >= 0; --i) {
    while (!stk4.empty() && a[i] >= a[stk4.top()]) {
      stk4.pop();
    }
    if (stk4.empty())
      r[i] = n;
    else
      r[i] = stk4.top();
    stk4.push(i);
  }
  for (int i = 0; i < n; ++i) {
    maxSum += (i - l[i]) * (r[i] - i) * a[i];
  }
  cout << maxSum - minSum << '\n';
}
