#include <bits/stdc++.h>
using namespace std;
const int N = 2000005;
int n, i, j, k, x, y, a[N], b[N], c[N], h[N], t[N], v[N], f[N], s[N], p[N],
    q[N];
long long u, o;
bool cmp(int x, int y) {
  if (a[x] != a[y]) return a[x] < a[y];
  return x < y;
}
bool Cmp(int x, int y) {
  if (a[x] != a[y]) return a[x] > a[y];
  return x < y;
}
int F(int x) { return x == f[x] ? x : f[x] = F(f[x]); }
int main() {
  scanf("%d", &n);
  for (i = 1; i <= n; ++i)
    scanf("%d", a + i), b[i] = c[i] = i, p[i] = q[i] = a[i], f[i] = i, s[i] = 1;
  sort(b + 1, b + n + 1, cmp);
  sort(c + 1, c + n + 1, Cmp);
  for (i = 1; i < n; i++) {
    scanf("%d%d", &x, &y);
    t[++k] = h[x];
    h[x] = k;
    v[k] = y;
    t[++k] = h[y];
    h[y] = k;
    v[k] = x;
  }
  for (i = 1; i <= n; i++) {
    x = b[i];
    y = 0;
    for (j = h[x]; j; j = t[j]) {
      k = F(v[j]);
      if (p[k] < p[x] || (p[k] == p[x] && k < x)) y += s[k];
    }
    u += 1ll * y * p[x];
    for (o = 0, j = h[x]; j; j = t[j]) {
      k = F(v[j]);
      if (p[k] < p[x] || (p[k] == p[x] && k < x))
        o += 1ll * s[k] * (y - s[k]) * p[x], f[k] = x, s[x] += s[k];
    }
    u += o / 2;
  }
  for (i = 1; i <= n; i++) f[i] = i, s[i] = 1;
  for (i = 1; i <= n; i++) {
    x = c[i];
    y = 0;
    for (j = h[x]; j; j = t[j]) {
      k = F(v[j]);
      if (q[k] > q[x] || (q[k] == q[x] && k < x)) y += s[k];
    }
    u -= 1ll * y * q[x];
    for (o = 0, j = h[x]; j; j = t[j]) {
      k = F(v[j]);
      if (q[k] > q[x] || (q[k] == q[x] && k < x))
        o -= 1ll * s[k] * (y - s[k]) * q[x], f[k] = x, s[x] += s[k];
    }
    u += o / 2;
  }
  printf("%I64d", u);
}
