#include <bits/stdc++.h>
using namespace std;
long long n, ans = 0;
vector<long long> a, pa, r;
vector<bool> vis;
vector<vector<long long>> g;
long long root(long long u) {
  if (pa[u] == u) return u;
  return pa[u] = root(pa[u]);
}
void union_set(long long u, long long v) {
  r[u] = r[u] + r[v];
  pa[v] = u;
}
void init() {
  cin >> n;
  a.resize(n + 1);
  pa.resize(n + 1);
  r.resize(n + 1);
  g.resize(n + 1);
  vis.resize(n + 1);
  for (long long i = 1; i <= n; i++) {
    cin >> a[i];
    pa[i] = i;
    vis[i] = false;
    r[i] = 1;
  }
  for (long long i = 1; i <= n - 1; i++) {
    long long u, v;
    cin >> u >> v;
    g[u].emplace_back(v);
    g[v].emplace_back(u);
  }
}
void reset() {
  for (long long i = 1; i <= n; i++) {
    pa[i] = i;
    r[i] = 1;
    vis[i] = false;
    a[i] = 0 - a[i];
  }
}
void solve() {
  vector<long long> vertex(n);
  iota((vertex).begin(), (vertex).end(), 1);
  sort((vertex).begin(), (vertex).end(),
       [&](const long long x, const long long y) { return a[x] < a[y]; });
  for (long long u : vertex) {
    vis[u] = true;
    for (long long v : g[u]) {
      if (vis[v] == true) {
        u = root(u);
        v = root(v);
        ans += (r[u] * r[v]) * a[u];
        union_set(u, v);
      }
    }
  }
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  init();
  solve();
  reset();
  solve();
  cout << ans;
  return 0;
}
