#include <bits/stdc++.h>
using namespace std;
struct node {
  int val;
  int ix;
  friend bool operator<(node x, node y) { return x.val < y.val; }
} a[1000100];
struct Edge {
  int to, nxt;
} edge[1000100 << 1];
int head[1000100];
int cnt;
void init() {
  memset(head, -1, sizeof(head));
  cnt = 0;
}
void ae(int u, int v) {
  edge[cnt].to = v;
  edge[cnt].nxt = head[u];
  head[u] = cnt++;
}
int f[1000100];
int siz[1000100];
int del[1000100];
int ff(int x) {
  if (f[x] == x) {
    return x;
  }
  while (f[x] != x) {
    f[x] = ff(f[x]);
    return f[x];
  }
}
void un(int u, int v) {
  int fu = ff(u);
  int fv = ff(v);
  f[fv] = fu;
  siz[fu] += siz[fv];
}
int main() {
  init();
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) a[i].ix = i;
  for (int i = 1; i <= n; i++) siz[i] = 1;
  for (int i = 1; i <= n; i++) scanf("%d", &a[i].val);
  for (int i = 1; i < n; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    ae(x, y);
    ae(y, x);
  }
  for (int i = 1; i <= n; i++) f[i] = i;
  sort(a + 1, a + 1 + n);
  long long tot_max = 0;
  long long tot_min = 0;
  for (int i = 1; i <= n; i++) {
    int r = a[i].ix;
    del[r] = 1;
    long long sum = 1;
    for (int j = head[r]; ~j; j = edge[j].nxt) {
      int to = edge[j].to;
      if (del[to]) {
        tot_max += 1ll * a[i].val * (siz[ff(to)] * sum);
        sum += siz[ff(to)];
        un(to, r);
      }
    }
  }
  memset(del, 0, sizeof(del));
  for (int i = 1; i <= n; i++) siz[i] = 1;
  for (int i = 1; i <= n; i++) f[i] = i;
  for (int i = n; i >= 1; i--) {
    int r = a[i].ix;
    del[r] = 1;
    long long sum = 1;
    for (int j = head[r]; ~j; j = edge[j].nxt) {
      int to = edge[j].to;
      if (del[to]) {
        tot_min += 1ll * a[i].val * (siz[ff(to)] * sum);
        sum += siz[ff(to)];
        un(to, r);
      }
    }
  }
  printf("%I64d\n", tot_max - tot_min);
  return 0;
}
