#include <bits/stdc++.h>
struct pnt {
  int hd;
  int val;
  int fa;
  int siz;
  bool vis;
} p[2000000];
struct ent {
  int twd;
  int lst;
} e[4000000];
struct int_2 {
  int no;
  int vl;
} tmp[2000000];
int cnt;
int n, m;
bool cmp(int_2 x, int_2 y) { return x.vl < y.vl; }
bool cmq(int_2 x, int_2 y) { return x.vl > y.vl; }
void ade(int f, int t) {
  cnt++;
  e[cnt].twd = t;
  e[cnt].lst = p[f].hd;
  p[f].hd = cnt;
  return;
}
int finf(int x) { return x == p[x].fa ? x : p[x].fa = finf(p[x].fa); }
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    tmp[i].no = i;
    scanf("%d", &tmp[i].vl);
    p[i].val = tmp[i].vl;
  }
  for (int i = 1; i < n; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    ade(a, b);
    ade(b, a);
  }
  long long ans1 = 0;
  std::sort(tmp + 1, tmp + n + 1, cmp);
  for (int i = 1; i <= n; i++) {
    p[i].fa = i;
    p[i].siz = 1;
    p[i].vis = false;
  }
  for (int g = 1; g <= n; g++) {
    int x = tmp[g].no;
    for (int i = p[x].hd; i; i = e[i].lst) {
      int to = e[i].twd;
      if (p[to].vis == false) continue;
      int ff = finf(to);
      ans1 += (long long)(p[ff].siz) * (long long)(p[x].siz) *
              (long long)(p[x].val);
      p[x].siz += p[ff].siz;
      p[ff].fa = x;
    }
    p[x].vis = true;
  }
  long long ans2 = 0;
  std::sort(tmp + 1, tmp + n + 1, cmq);
  for (int i = 1; i <= n; i++) {
    p[i].fa = i;
    p[i].siz = 1;
    p[i].vis = false;
  }
  for (int g = 1; g <= n; g++) {
    int x = tmp[g].no;
    for (int i = p[x].hd; i; i = e[i].lst) {
      int to = e[i].twd;
      if (p[to].vis == false) continue;
      int ff = finf(to);
      ans2 += (long long)(p[ff].siz) * (long long)(p[x].siz) *
              (long long)(p[x].val);
      p[x].siz += p[ff].siz;
      p[ff].fa = x;
    }
    p[x].vis = true;
  }
  printf("%I64d\n", ans1 - ans2);
  return 0;
}
