#include <bits/stdc++.h>
using namespace std;
long long p[2000005], sz[2000005];
vector<long long> g[2000005];
long long find1(long long u) {
  while (u != p[u]) {
    p[u] = p[p[u]];
    u = p[u];
  }
  return u;
}
void unn(long long u, long long v) {
  u = find1(u);
  v = find1(v);
  if (u == v) return;
  if (sz[u] > sz[v]) swap(u, v);
  sz[v] += sz[u];
  p[u] = v;
}
int32_t main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  long long n;
  cin >> n;
  for (long long i = 0; i <= n; i++) {
    sz[i] = 1;
    p[i] = i;
  }
  long long arr[n + 1];
  vector<pair<long long, long long> > v;
  for (long long i = 1; i <= n; i++) {
    long long x;
    cin >> x;
    arr[i] = x;
    v.push_back({x, i});
  }
  sort(v.begin(), v.end());
  for (long long i = 0; i < n - 1; i++) {
    long long u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  long long ans = 0;
  unordered_map<long long, long long> mp;
  for (long long i = 0; i < v.size(); i++) {
    long long x = v[i].first;
    long long u = v[i].second;
    long long sum = 0, sqsum = 0;
    for (long long j = 0; j < g[u].size(); j++) {
      long long y = g[u][j];
      if (mp.find(y) == mp.end()) continue;
      long long a = find1(y);
      sum += sz[a];
      sqsum += sz[a] * sz[a];
      unn(u, y);
    }
    long long paths = sum + 1;
    paths += (sum * sum - sqsum) / 2LL;
    ans += paths * x;
    mp[u];
  }
  mp.clear();
  for (long long i = 0; i <= n; i++) {
    sz[i] = 1;
    p[i] = i;
  }
  reverse(v.begin(), v.end());
  for (long long i = 0; i < v.size(); i++) {
    long long x = v[i].first;
    long long u = v[i].second;
    long long sum = 0, sqsum = 0;
    for (long long j = 0; j < g[u].size(); j++) {
      long long y = g[u][j];
      if (mp.find(y) == mp.end()) continue;
      long long a = find1(y);
      sum += sz[a];
      sqsum += sz[a] * sz[a];
      unn(u, y);
    }
    long long paths = sum + 1;
    paths += (sum * sum - sqsum) / 2LL;
    ans -= paths * x;
    mp[u];
  }
  cout << ans;
  return 0;
}
