#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int n, i, x, y, a[N], g[N], v[N << 1], nxt[N << 1], ed;
int q[N];
int f[N], size[N];
long long cur;
inline bool cmp(int x, int y) { return a[x] < a[y]; }
inline void add(int x, int y) {
  v[++ed] = y;
  nxt[ed] = g[x];
  g[x] = ed;
}
int F(int x) { return f[x] == x ? x : f[x] = F(f[x]); }
inline void merge(int x, int y, int z) {
  if (!f[x] || !f[y]) return;
  x = F(x), y = F(y);
  cur += 1LL * z * size[x] * size[y];
  f[x] = y;
  size[y] += size[x];
}
long long cal() {
  for (i = 1; i <= n; i++) q[i] = i;
  sort(q + 1, q + n + 1, cmp);
  for (i = 1; i <= n; i++) f[i] = size[i] = 0;
  cur = 0;
  for (i = 1; i <= n; i++) {
    int x = q[i];
    f[x] = x, size[x] = 1;
    for (int j = g[x]; j; j = nxt[j]) merge(x, v[j], a[x]);
  }
  return cur;
}
int main() {
  scanf("%d", &n);
  for (i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (i = 1; i < n; i++) scanf("%d%d", &x, &y), add(x, y), add(y, x);
  long long ans1 = cal();
  for (i = 1; i <= n; i++) a[i] *= -1;
  long long ans2 = cal();
  printf("%I64d", ans1 + ans2);
}
