#include <bits/stdc++.h>
using namespace std;
int n;
int w[1000005];
int p[1000005], size[1000005];
struct edge {
  int u, v, w0, w1;
  edge(int u = 0, int v = 0, int w0 = 0, int w1 = 0)
      : u(u), v(v), w0(w0), w1(w1) {}
} elist[1000005];
bool cmp0(const edge& e1, const edge& e2) { return e1.w0 < e2.w0; }
bool cmp1(const edge& e1, const edge& e2) { return e1.w1 < e2.w1; }
int fr(int x) {
  if (p[x] == x)
    return x;
  else
    return p[x] = fr(p[x]);
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &w[i]);
  }
  int u, v, w0, w1;
  for (int i = 1; i <= n - 1; i++) {
    scanf("%d%d", &u, &v);
    w0 = min(w[u], w[v]);
    w1 = max(w[u], w[v]);
    elist[i] = edge(u, v, w0, w1);
  }
  long long ans0 = 0;
  long long ans1 = 0;
  sort(elist + 1, elist + 1 + n, cmp1);
  for (int i = 1; i <= n; i++) {
    p[i] = i;
    size[i] = 1;
  }
  int ru, rv;
  for (int i = 1; i <= n; i++) {
    u = elist[i].u;
    v = elist[i].v;
    ru = fr(u);
    rv = fr(v);
    ans1 += (long long)(size[ru]) * size[rv] * elist[i].w1;
    p[ru] = rv;
    size[rv] += size[ru];
  }
  sort(elist + 1, elist + 1 + n, cmp0);
  for (int i = 1; i <= n; i++) {
    p[i] = i;
    size[i] = 1;
  }
  for (int i = n; i >= 1; i--) {
    u = elist[i].u;
    v = elist[i].v;
    ru = fr(u);
    rv = fr(v);
    ans0 += (long long)(size[ru]) * size[rv] * elist[i].w0;
    p[ru] = rv;
    size[rv] += size[ru];
  }
  printf("%lld", ans1 - ans0);
}
