#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
vector<int> e[N];
vector<int> parent, siz, vis;
void init(int n) {
  parent = siz = vis = vector<int>(n);
  for (int i = 0; i < n; i++) {
    parent[i] = i;
    siz[i] = 1;
    vis[i] = 0;
  }
}
int find(int a) { return a == parent[a] ? a : parent[a] = find(parent[a]); }
void join(int a, int b) {
  b = find(b);
  a = find(a);
  if (a == b) return;
  parent[b] = a;
  siz[a] += siz[b];
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  vector<pair<int, int> > w(n, {0, 0});
  for (int i = 0; i < n; i++) {
    int t;
    cin >> t;
    w[i] = {t, i};
  }
  auto addedge = [&](int x, int y) {
    e[x].push_back(y);
    e[y].push_back(x);
  };
  for (int i = 1; i < n; i++) {
    int x, y;
    cin >> x >> y;
    x--;
    y--;
    addedge(x, y);
  }
  sort(w.begin(), w.end());
  init(n);
  long long ans = 0;
  for (auto p : w) {
    long long cnt = 0;
    vis[p.second] = 1;
    for (int nei : e[p.second]) {
      if (vis[nei]) {
        int pa = find(nei);
        cnt += 1LL * siz[p.second] * siz[pa];
        join(p.second, pa);
      }
    }
    ans += p.first * cnt;
  }
  reverse(w.begin(), w.end());
  init(n);
  for (auto p : w) {
    long long cnt = 0;
    vis[p.second] = true;
    for (int nei : e[p.second]) {
      if (vis[nei]) {
        int pa = find(nei);
        cnt += 1LL * siz[p.second] * siz[pa];
        join(p.second, pa);
      }
    }
    ans -= p.first * cnt;
  }
  cout << ans << endl;
  return 0;
}
