#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e6 + 7;
const long long mod = 1e9 + 9;
const long long INF = 1e9 + 7;
const long long mlog = 21;
const long long SQ = 400;
long long n;
long long a[maxn];
long long f[maxn], nxt[maxn];
bool mark[maxn];
vector<long long> adj[maxn];
long long get(long long u) { return nxt[u] < 0 ? u : nxt[u] = get(nxt[u]); }
void merge(long long a, long long b) {
  a = get(a);
  b = get(b);
  if (a == b) return;
  if (nxt[a] > nxt[b]) swap(a, b);
  nxt[a] += nxt[b];
  nxt[b] = a;
}
long long solve() {
  memset(nxt, -1, sizeof nxt);
  memset(mark, 0, sizeof mark);
  long long ans = 0;
  for (long long i = 1; i <= n; i++) {
    long long u = f[i];
    mark[u] = 1;
    long long num = 0, Sum = 1;
    for (long long y : adj[u]) {
      if (mark[y]) {
        long long second = -nxt[get(y)];
        num += Sum * second;
        Sum += second;
        merge(u, y);
      }
    }
    ans += num * a[u];
  }
  return ans;
}
int32_t main() {
  ios_base::sync_with_stdio(false), cin.tie(), cout.tie();
  ;
  cin >> n;
  for (long long i = 1; i <= n; i++) cin >> a[i];
  for (long long i = 1; i <= n - 1; i++) {
    long long a, b;
    cin >> a >> b;
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  for (long long i = 1; i <= n; i++) f[i] = i;
  sort(f + 1, f + n + 1, [](long long x, long long y) { return a[x] < a[y]; });
  long long ans = solve();
  reverse(f + 1, f + n + 1);
  ans -= solve();
  cout << ans << "\n";
  return 0;
}
