#include <bits/stdc++.h>
using namespace std;
struct Nod {
  int x, y;
} a[2000005];
int i, j, k, l, n, m, x, y, X;
int Len, Next[2000005], Link[2000005], Son[2000005], Now;
int Fa[2000005], Vis[2000005], Size[2000005];
int Map[2000005];
long long ans, tmp;
inline void Add(int x, int y) {
  Next[++Len] = Son[x];
  Son[x] = Len;
  Link[Len] = y;
}
inline bool cmp(const Nod &l, const Nod &r) { return l.x < r.x; }
inline int GetFa(int x) { return Fa[x] == x ? x : Fa[x] = GetFa(Fa[x]); }
int main() {
  scanf("%d", &n);
  for (i = 1; i <= n; i++) {
    scanf("%d", &a[i].x);
    a[i].y = i;
  }
  sort(a + 1, a + n + 1, cmp);
  for (i = 1; i <= n; i++) Map[a[i].y] = i;
  for (i = 1; i < n; i++) {
    scanf("%d%d", &x, &y);
    Add(Map[x], Map[y]);
    Add(Map[y], Map[x]);
  }
  for (i = 1; i <= n; i++) Fa[i] = i;
  for (i = 1; i <= n; i++) Size[i] = 1;
  for (i = 1; i <= n; i++) {
    Vis[i] = 1;
    tmp = 0;
    for (Now = Son[i]; Now; Now = Next[Now])
      if (Vis[Link[Now]]) {
        X = GetFa(Link[Now]);
        if (Size[i] == 1)
          tmp = 1ll * Size[X];
        else
          tmp += 1ll * Size[i] * Size[X];
        Size[i] += Size[X];
        Fa[X] = i;
      }
    ans += tmp * a[i].x;
  }
  for (i = n; i; i--) Fa[i] = i;
  memset(Vis, 0, sizeof(Vis));
  for (i = 1; i <= n; i++) Size[i] = 1;
  for (i = n; i; i--) {
    Vis[i] = 1;
    tmp = 0;
    for (Now = Son[i]; Now; Now = Next[Now])
      if (Vis[Link[Now]]) {
        X = GetFa(Link[Now]);
        if (Size[i] == 1)
          tmp = 1ll * (Size[X]);
        else
          tmp += 1ll * (Size[i]) * Size[X];
        Size[i] += Size[X];
        Fa[X] = i;
      }
    ans -= tmp * a[i].x;
  }
  printf("%I64d", ans);
}
