#include <bits/stdc++.h>
using namespace std;
int readl() {
  int x = 0, fg = 1;
  char ch = getchar();
  while (ch > '9' || ch < '0') {
    if (ch == '-') fg = -fg;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = (x << 1) + (x << 3) + (ch ^ 48);
    ch = getchar();
  }
  return fg * x;
}
int n, cnt = 0, a[1000100], f[1000100];
long long sz[1000100];
struct nd {
  int u, v;
  long long val, valn;
} c[1000100];
vector<int> vec[1000100];
int find(int x) {
  if (f[x] != x) f[x] = find(f[x]);
  return f[x];
}
int cmp(nd xx, nd yy) { return xx.val < yy.val; }
int cmp1(nd xx, nd yy) { return xx.valn > yy.valn; }
int main() {
  n = readl();
  for (int i = 1; i <= n; i++) a[i] = readl();
  int x, y;
  for (int i = 1; i < n; i++) {
    x = readl();
    y = readl();
    c[i].u = x;
    c[i].v = y;
    c[i].val = max(a[x], a[y]);
    c[i].valn = min(a[x], a[y]);
  }
  long long ans = 0;
  sort(c + 1, c + n, cmp);
  for (int i = 1; i <= n + 1; i++) {
    f[i] = i;
    sz[i] = 1;
  }
  for (int i = 1; i < n; i++) {
    int fu = find(c[i].u), fv = find(c[i].v);
    ans += sz[fu] * sz[fv] * c[i].val;
    f[fu] = fv;
    sz[fv] += sz[fu];
  }
  sort(c + 1, c + n, cmp1);
  for (int i = 1; i <= n + 1; i++) {
    f[i] = i;
    sz[i] = 1;
  }
  for (int i = 1; i <= n; i++) {
    int fu = find(c[i].u), fv = find(c[i].v);
    ans -= sz[fu] * sz[fv] * c[i].valn;
    f[fu] = fv;
    sz[fv] += sz[fu];
  }
  printf("%lld", ans);
  return 0;
}
