#include <bits/stdc++.h>
using namespace std;
int arr[1000100];
int l[1000100], r[1000100];
stack<int> s;
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> arr[i];
  }
  for (int i = 1; i <= n; i++) {
    while (!s.empty()) {
      if (arr[s.top()] >= arr[i]) {
        r[s.top()] = i - 1;
        s.pop();
      } else {
        l[i] = s.top() + 1;
        break;
      }
    }
    if (s.empty()) l[i] = 1;
    s.push(i);
  }
  while (!s.empty()) {
    r[s.top()] = n;
    s.pop();
  }
  long long int ans = 0;
  for (int i = 1; i <= n; i++) {
    ans += 1LL * arr[i] * (r[i] - i + 1) * (i - l[i] + 1);
  }
  for (int i = 1; i <= n; i++) {
    while (!s.empty()) {
      if (arr[s.top()] <= arr[i]) {
        r[s.top()] = i - 1;
        s.pop();
      } else {
        l[i] = s.top() + 1;
        break;
      }
    }
    if (s.empty()) l[i] = 1;
    s.push(i);
  }
  while (!s.empty()) {
    r[s.top()] = n;
    s.pop();
  }
  for (int i = 1; i <= n; i++) {
    ans -= 1LL * arr[i] * (r[i] - i + 1) * (i - l[i] + 1);
  }
  cout << -1LL * ans;
  return 0;
}
