#include <bits/stdc++.h>
using namespace std;
inline void read(int& x) {
  x = 0;
  char c = getchar();
  while (c < '0' || c > '9') c = getchar();
  while (c >= '0' && c <= '9') {
    x = (x << 3) + (x << 1) + (c ^ 48);
    c = getchar();
  }
}
struct edge {
  int u, v, w;
  inline edge(int u = 0, int v = 0, int w = 0) : u(u), v(v), w(w) {}
  inline bool operator<(const edge& x) const { return w < x.w; }
} e[1000003];
int fa[1000003], a[1000003], size[1000003];
int n;
long long ans;
inline int find(int x) {
  while (x != fa[x]) x = fa[x] = fa[fa[x]];
  return x;
}
inline void merge(int u, int v, int w) {
  u = find(u), v = find(v);
  ans += (long long)w * size[u] * size[v];
  fa[u] = v;
  size[v] += size[u];
}
int main() {
  int u, v;
  read(n);
  for (register int i = 1; i <= n; ++i) read(a[i]);
  for (register int i = 1; i < n; ++i) {
    read(u), read(v);
    e[i] = edge(u, v, min(a[u], a[v]));
    fa[i] = i;
    size[i] = 1;
  }
  fa[n] = n, size[n] = 1;
  sort(e + 1, e + n);
  for (register int i = n - 1; i; --i) merge(e[i].u, e[i].v, e[i].w);
  ans = -ans;
  for (register int i = 1; i <= n; ++i) fa[i] = i, size[i] = 1;
  for (register int i = 1; i < n; ++i) e[i].w = max(a[e[i].u], a[e[i].v]);
  sort(e + 1, e + n);
  for (register int i = 1; i < n; ++i) merge(e[i].u, e[i].v, e[i].w);
  printf("%I64d", ans);
  return 0;
}
