#include <bits/stdc++.h>
using namespace std;
int n, tot, f[1000005], s[1000005], ver[2000005], nxt[2000005], head[1000005];
bool used[1000005];
long long ans;
struct node {
  int x, id;
} a[1000005];
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  for (; !isdigit(ch); ch = getchar())
    if (ch == '-') f = -1;
  for (; isdigit(ch); ch = getchar()) x = (x + (x << 2) << 1) + (ch ^ 48);
  return x * f;
}
bool cmp1(const node &x, const node &y) { return x.x < y.x; }
bool cmp2(const node &x, const node &y) { return x.x > y.x; }
void add(int x, int y) { ver[++tot] = y, nxt[tot] = head[x], head[x] = tot; }
int getf(int x) {
  if (x == f[x]) return x;
  return f[x] = getf(f[x]);
}
int main() {
  n = read();
  for (int i = 1; i <= n; i++) a[i].x = read(), f[i] = a[i].id = i, s[i] = 1;
  for (int i = 1; i < n; i++) {
    int x = read(), y = read();
    add(x, y), add(y, x);
  }
  sort(a + 1, a + n + 1, cmp1);
  for (int i = 1; i <= n; i++) {
    int x = a[i].id;
    used[x] = 1;
    for (int j = head[x]; j; j = nxt[j])
      if (used[ver[j]]) {
        int y = getf(ver[j]);
        ans += (long long)s[y] * s[x] * a[i].x, s[x] += s[y], f[y] = x;
      }
  }
  for (int i = 1; i <= n; i++) f[i] = i, s[i] = 1;
  sort(a + 1, a + n + 1, cmp2);
  for (int i = 1; i <= n; i++) {
    int x = a[i].id;
    used[x] = 0;
    for (int j = head[x]; j; j = nxt[j])
      if (!used[ver[j]]) {
        int y = getf(ver[j]);
        ans -= (long long)s[y] * s[x] * a[i].x, s[x] += s[y], f[y] = x;
      }
  }
  printf("%lld", ans);
  return 0;
}
