#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  long long int n;
  cin >> n;
  long long int a[n];
  long long int greaterright[n];
  long long int greaterleft[n];
  long long int smallerright[n];
  long long int smallerleft[n];
  for (long long int i = 0; i < n; i++) {
    cin >> a[i];
  }
  stack<pair<long long int, long long int> > s;
  for (long long int i = n - 1; i >= 0; i--) {
    while (!s.empty() && a[i] >= s.top().first) {
      s.pop();
    }
    if (s.empty()) {
      greaterright[i] = n;
    } else {
      greaterright[i] = s.top().second;
    }
    s.push(make_pair(a[i], i));
  }
  while (!s.empty()) s.pop();
  for (long long int i = 0; i <= n; i++) {
    while (!s.empty() && a[i] > s.top().first) {
      s.pop();
    }
    if (s.empty()) {
      greaterleft[i] = -1;
    } else {
      greaterleft[i] = s.top().second;
    }
    s.push(make_pair(a[i], i));
  }
  while (!s.empty()) s.pop();
  for (long long int i = 0; i <= n; i++) {
    while (!s.empty() && a[i] < s.top().first) {
      s.pop();
    }
    if (s.empty()) {
      smallerleft[i] = -1;
    } else {
      smallerleft[i] = s.top().second;
    }
    s.push(make_pair(a[i], i));
  }
  while (!s.empty()) s.pop();
  for (long long int i = n - 1; i >= 0; i--) {
    while (!s.empty() && a[i] <= s.top().first) {
      s.pop();
    }
    if (s.empty()) {
      smallerright[i] = n;
    } else {
      smallerright[i] = s.top().second;
    }
    s.push(make_pair(a[i], i));
  }
  long long int ans = 0;
  for (long long int i = 0; i < n; i++) {
    long long int left_elements = i - greaterleft[i];
    long long int right_element = greaterright[i] - i;
    ans += a[i] * left_elements * right_element;
  }
  for (long long int i = 0; i < n; i++) {
    long long int left_elements = i - smallerleft[i];
    long long int right_element = smallerright[i] - i;
    ans -= a[i] * left_elements * right_element;
  }
  cout << ans << endl;
  return 0;
}
