#include <bits/stdc++.h>
using namespace std;
long long n, m, k, l, i, j, a, b, sz[1000005], par[1000005], fx[1000005], res;
vector<long long> v[1000005];
queue<long long> q;
pair<long long, long long> d[1000005];
long long find_set(long long v) {
  if (v == par[v]) return v;
  return par[v] = find_set(par[v]);
}
void union_sets(long long a, long long b) {
  a = find_set(a);
  b = find_set(b);
  if (sz[a] < sz[b]) swap(a, b);
  par[b] = a;
  sz[a] += sz[b];
}
int main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    scanf("%lld", &d[i].first);
    d[i].second = i;
  }
  for (long long i = 0; i < n - 1; i++) {
    scanf("%lld%lld", &a, &b);
    v[a].push_back(b);
    v[b].push_back(a);
  }
  for (long long i = 1; i <= n; i++) {
    sz[i] = 1;
    par[i] = i;
    fx[i] = 0;
  }
  sort(d + 1, d + 1 + n);
  for (long long i = 1; i <= n; i++) {
    long long x = d[i].second, s = 0, sq = 0;
    for (auto j : v[x]) {
      if (fx[j] == 0) continue;
      sq += sz[find_set(j)] * sz[find_set(j)];
      s += sz[find_set(j)];
      union_sets(x, j);
    }
    s = (s * s - sq) / 2;
    s += sz[find_set(x)];
    res += s * d[i].first;
    fx[x] = 1;
  }
  for (long long i = 1; i <= n; i++) {
    sz[i] = 1;
    par[i] = i;
    fx[i] = 0;
  }
  reverse(d + 1, d + 1 + n);
  for (long long i = 1; i <= n; i++) {
    long long x = d[i].second, s = 0, sq = 0;
    for (auto j : v[x]) {
      if (fx[j] == 0) continue;
      sq += sz[find_set(j)] * sz[find_set(j)];
      s += sz[find_set(j)];
      union_sets(x, j);
    }
    s = (s * s - sq) / 2;
    s += sz[find_set(x)];
    res -= s * d[i].first;
    fx[x] = 1;
  }
  cout << res;
}
