#include <bits/stdc++.h>
using namespace std;
const int MAXB = 3e7;
char buf[MAXB], *cp = buf;
inline void rd(int &x) {
  x = 0;
  int f = 1;
  while (*cp < '0' || '9' < *cp) {
    if (*cp == '-') f = -1;
    cp++;
  }
  while ('0' <= *cp && *cp <= '9') x = (x << 3) + (x << 1) + *cp - 48, cp++;
  x *= f;
}
inline int min(int x, int y) { return x < y ? x : y; }
inline int max(int x, int y) { return x > y ? x : y; }
const int MAXN = 1000010;
pair<int, pair<int, int> > e[MAXN];
int v[MAXN];
int f[MAXN], sz[MAXN], h[MAXN];
int n;
long long ans;
inline int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); }
inline void uni(int x, int y) {
  x = find(x);
  y = find(y);
  if (h[x] < h[y]) swap(x, y);
  if (h[x] == h[y]) h[x]++;
  sz[x] += sz[y];
  f[y] = x;
}
int main() {
  buf[fread(buf, 1, MAXB, stdin)] = 0;
  rd(n);
  for (int i = 1; i <= n; i++) rd(v[i]);
  for (int i = 0; i < n - 1; i++) {
    rd(e[i].second.first);
    rd(e[i].second.second);
  }
  for (int i = 0; i < n - 1; i++)
    e[i].first = max(v[e[i].second.first], v[e[i].second.second]);
  sort(e, e + n - 1);
  for (int i = 1; i <= n; i++) f[i] = i, sz[i] = h[i] = 1;
  for (int i = 0; i < n - 1; i++) {
    ans += (long long)e[i].first * sz[find(e[i].second.first)] *
           sz[find(e[i].second.second)];
    uni(e[i].second.first, e[i].second.second);
  }
  for (int i = 0; i < n - 1; i++)
    e[i].first = min(v[e[i].second.first], v[e[i].second.second]);
  sort(e, e + n - 1, greater<pair<int, pair<int, int> > >());
  for (int i = 1; i <= n; i++) f[i] = i, sz[i] = h[i] = 1;
  for (int i = 0; i < n - 1; i++) {
    ans -= (long long)e[i].first * sz[find(e[i].second.first)] *
           sz[find(e[i].second.second)];
    uni(e[i].second.first, e[i].second.second);
  }
  printf("%I64d\n", ans);
  return 0;
}
