#include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
int n, a[N + 5], id[N + 5], fa[N + 5], siz[N + 5];
bool vis[N + 5];
vector<int> e[N + 5];
inline int Find(int x) {
  while (fa[x] != x) x = fa[x] = fa[fa[x]];
  return x;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
  for (int i = 1, u, v; i < n; ++i) {
    scanf("%d%d", &u, &v);
    e[u].push_back(v);
    e[v].push_back(u);
  }
  long long ans = 0;
  for (int i = 1; i <= n; ++i) {
    siz[i] = 1;
    vis[i] = false;
    id[i] = fa[i] = i;
  }
  sort(id + 1, id + 1 + n,
       [](const int &x, const int &y) { return a[x] < a[y]; });
  for (int i = 1; i <= n; ++i) {
    int u = id[i], fu = Find(u);
    long long sum = 1;
    for (const int &v : e[u])
      if (vis[v]) sum += siz[Find(v)];
    for (const int &v : e[u])
      if (vis[v]) {
        int fv = Find(v);
        ans += (sum - siz[fv]) * siz[fv] * a[u];
        sum -= siz[fv];
        fa[fv] = fu;
        siz[fu] += siz[fv];
      }
    vis[u] = true;
  }
  for (int i = 1; i <= n; ++i) {
    siz[i] = 1;
    vis[i] = false;
    fa[i] = i;
  }
  for (int i = n; i >= 1; --i) {
    int u = id[i], fu = Find(u);
    long long sum = 1;
    for (const int &v : e[u])
      if (vis[v]) sum += siz[Find(v)];
    for (const int &v : e[u])
      if (vis[v]) {
        int fv = Find(v);
        ans -= (sum - siz[fv]) * siz[fv] * a[u];
        sum -= siz[fv];
        fa[fv] = fu;
        siz[fu] += siz[fv];
      }
    vis[u] = true;
  }
  printf("%lld\n", ans);
  return 0;
}
