#include <bits/stdc++.h>
using namespace std;
struct node {
  long long su, id;
} a[1000003];
long long n, x, y, vis[1000003], ans, fa[1000003], fv, siz[1000003];
vector<long long> l[1000003];
long long cmp(node nx, node ny) { return nx.su < ny.su; }
long long find(long long x1) {
  while (fa[x1] != x1) fa[x1] = fa[fa[x1]], x1 = fa[x1];
  return x1;
}
void f(long long x1, long long sum) {
  for (long long j = 0; j < l[x1].size(); j++) {
    fv = find(l[x1][j]);
    if (vis[fv] == 0) continue;
    ans += siz[fv] * siz[x1] * sum, siz[x1] += siz[fv], fa[fv] = x1;
  }
}
signed main() {
  scanf("%d", &n);
  for (long long i = 1; i <= n; i++) {
    a[i].id = i, fa[i] = i, siz[i] = 1;
    scanf("%d", &a[i].su);
  }
  for (long long i = 1; i < n; i++) {
    scanf("%d%d", &x, &y);
    l[x].push_back(y), l[y].push_back(x);
  }
  sort(a + 1, a + n + 1, cmp);
  for (long long i = 1; i <= n; i++) {
    f(a[i].id, a[i].su);
    vis[a[i].id] = 1, a[i].su *= -1;
  }
  for (long long i = 1; i <= n; i++) fa[i] = i, siz[i] = 1, vis[i] = 0;
  for (long long i = n; i >= 1; i--) {
    f(a[i].id, a[i].su);
    vis[a[i].id] = 1;
  }
  cout << ans;
  return 0;
}
