#include <bits/stdc++.h>
using namespace std;
const int Maxn = 1e6 + 5;
int n, x, y;
vector<int> adj[Maxn];
pair<int, int> a[Maxn];
int f[Maxn];
int sz[Maxn];
long long maxt = 0, mint = 0;
int find(int x) {
  if (f[x] == x) return x;
  return f[x] = find(f[x]);
}
void init() {
  for (int i = 1; i <= n; i++) {
    f[i] = i;
    sz[i] = 0;
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i].first);
    a[i].second = i;
  }
  for (int i = 1; i < n; i++) {
    scanf("%d%d", &x, &y);
    adj[x].push_back(y);
    adj[y].push_back(x);
  }
  sort(a + 1, a + n + 1);
  init();
  for (int i = 1; i <= n; i++) {
    long long sum = 0, square = 0;
    sz[a[i].second] = 1;
    for (auto v : adj[a[i].second]) {
      find(v);
      sum += sz[f[v]];
      square += (long long)sz[f[v]] * sz[f[v]];
      if (sz[f[v]] != 0) {
        sz[a[i].second] += sz[f[v]];
        f[f[v]] = a[i].second;
      }
    }
    maxt += (sum + 1) * a[i].first;
    maxt += (sum * sum - square) * a[i].first / 2;
  }
  init();
  for (int i = n; i >= 1; i--) {
    long long sum = 0, square = 0;
    sz[a[i].second] = 1;
    for (auto v : adj[a[i].second]) {
      find(v);
      sum += sz[f[v]];
      square += (long long)sz[f[v]] * sz[f[v]];
      if (sz[f[v]] != 0) {
        sz[a[i].second] += sz[f[v]];
        f[f[v]] = a[i].second;
      }
    }
    mint += (sum + 1) * a[i].first;
    mint += (sum * sum - square) * a[i].first / 2;
  }
  printf("%I64d\n", maxt - mint);
  return 0;
}
