#include <bits/stdc++.h>
using namespace std;
class union_find {
 public:
  vector<int> arr;
  union_find(int n) {
    arr.resize(n);
    fill(arr.begin(), arr.end(), -1);
  }
  int find(int x) { return arr[x] < 0 ? x : arr[x] = find(arr[x]); }
  void unite(int x, int y) {
    x = find(x), y = find(y);
    if (x == y) return;
    if (arr[x] > arr[y]) swap(x, y);
    arr[x] += arr[y];
    arr[y] = x;
  }
  bool connected(int x, int y) { return find(x) == find(y); }
  int size(int x) { return -arr[find(x)]; }
};
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  vector<long long> a(n);
  for (int i = 0; i < n; i++) cin >> a[i];
  vector<vector<int>> ad(n);
  for (int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    u--, v--;
    ad[u].push_back(v);
    ad[v].push_back(u);
  }
  vector<int> in(n);
  for (int i = 0; i < n; i++) in[i] = i;
  sort(in.begin(), in.end(), [&](int i0, int i1) { return a[i0] < a[i1]; });
  union_find uf0(n), uf1(n);
  long long res0 = 0, res1 = 0;
  vector<bool> ju(n);
  for (int i = 0; i < n; i++) {
    int cur = in[i];
    long long sum = 0, sum2 = 0;
    for (int ch : ad[cur]) {
      if (!ju[ch]) continue;
      long long v = uf0.size(ch);
      sum += v;
      sum2 += v * v;
      uf0.unite(ch, cur);
    }
    res0 += (sum + (sum * sum - sum2) / 2) * a[cur];
    ju[cur] = true;
  }
  fill(ju.begin(), ju.end(), false);
  for (int i = n - 1; i >= 0; i--) {
    int cur = in[i];
    long long sum = 0, sum2 = 0;
    for (int ch : ad[cur]) {
      if (!ju[ch]) continue;
      long long v = uf1.size(ch);
      sum += v;
      sum2 += v * v;
      uf1.unite(ch, cur);
    }
    res1 += (sum + (sum * sum - sum2) / 2) * a[cur];
    ju[cur] = true;
  }
  cout << (res0 - res1) << "\n";
  return 0;
}
