#include <bits/stdc++.h>
using namespace std;
int n, a[2000000], fa[2000000];
long long ans, size[2000000];
struct arr {
  int x, y;
  long long v1, v2;
} b[2000000];
bool cmp1(arr x, arr y) { return x.v2 < y.v2; }
bool cmp2(arr x, arr y) { return x.v1 > y.v1; }
int find(int x) {
  if (fa[x] == x) return x;
  fa[x] = find(fa[x]);
  return fa[x];
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i < n; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    b[i] = {x, y, min(a[x], a[y]), max(a[x], a[y])};
  }
  sort(b + 1, b + n, cmp1);
  for (int i = 1; i <= n; i++) fa[i] = i, size[i] = 1;
  for (int i = 1; i < n; i++) {
    int x = find(b[i].x), y = find(b[i].y);
    ans = ans + b[i].v2 * size[x] * size[y];
    fa[x] = y;
    size[y] += size[x];
  }
  sort(b + 1, b + n, cmp2);
  for (int i = 1; i <= n; i++) fa[i] = i, size[i] = 1;
  for (int i = 1; i < n; i++) {
    int x = find(b[i].x), y = find(b[i].y);
    ans = ans - b[i].v1 * size[x] * size[y];
    fa[x] = y;
    size[y] += size[x];
  }
  printf("%lld", ans);
  return 0;
}
