#include <bits/stdc++.h>
using namespace std;
void print() { cout << '\n'; }
template <class T, class... U>
void print(T x, U... y) {
  cout << x << ' ';
  print(y...);
}
const int N = 1e6 + 5, M = 1e9 + 7;
void Main();
int main(int argc, char **argv) {
  ios::sync_with_stdio(0), cin.tie(0);
  cout << setprecision(10) << fixed;
  Main();
}
int a[N], st[N];
long long solve(int n) {
  int s = 0, t = 0;
  long long ans = 0, sum = 0;
  for (int i = 1; i <= n; i++) {
    while (s < t && a[st[t]] < a[i])
      sum -= 1ll * a[st[t]] * (st[t] - st[t - 1]), t--;
    st[++t] = i;
    sum += 1ll * a[i] * (st[t] - st[t - 1]);
    ans += sum;
  }
  return ans;
}
void Main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  long long ans = solve(n);
  for (int i = 1; i <= n; i++) a[i] = -a[i];
  ans += solve(n);
  cout << ans << '\n';
}
