#include <bits/stdc++.h>
using namespace std;
class DSU {
 private:
  vector<long long> parent;
  vector<long long> size;

 public:
  DSU(long long n) {
    parent.resize(n);
    iota(parent.begin(), parent.end(), 0);
    size.resize(n, 1);
  }
  long long get(long long a) {
    if (parent[a] == a)
      return a;
    else
      return parent[a] = get(parent[a]);
  }
  bool merge(long long a, long long b) {
    a = get(a);
    b = get(b);
    if (a == b) return false;
    if (size[b] > size[a]) swap(a, b);
    parent[b] = a;
    size[a] += size[b];
    return true;
  }
  long long sz(long long a) {
    a = get(a);
    return size[a];
  }
};
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  vector<long long> order(n);
  iota(order.begin(), order.end(), 0ll);
  vector<long long> a(n);
  for (long long &i : a) cin >> i;
  vector<vector<long long>> tree(n);
  for (long long i = 0; i < n - 1; i++) {
    long long u, v;
    cin >> u >> v;
    u--;
    v--;
    tree[u].push_back(v);
    tree[v].push_back(u);
  }
  auto get = [&](long long type) {
    DSU D(n);
    vector<bool> visited(n, false);
    long long ans = 0;
    for (long long node : order) {
      vector<long long> joinees;
      for (long long i : tree[node]) {
        if (type == 1) {
          if (a[i] <= a[node] && visited[i]) joinees.push_back(D.sz(i));
        } else if (a[i] >= a[node] && visited[i])
          joinees.push_back(D.sz(i));
      }
      long long sum = accumulate(joinees.begin(), joinees.end(), 0ll);
      ans += sum * a[node];
      for (long long i : joinees) {
        ans += ((sum - i) * i) * a[node];
        sum -= i;
      }
      for (long long i : tree[node]) {
        if (type == 1) {
          if (a[i] <= a[node] && visited[i]) D.merge(node, i);
        } else if (a[i] >= a[node] && visited[i])
          D.merge(node, i);
      }
      visited[node] = true;
    }
    return ans;
  };
  sort(order.begin(), order.end(),
       [&](const long long &i, const long long &j) { return a[i] < a[j]; });
  long long mx = get(1);
  sort(order.begin(), order.end(),
       [&](const long long &i, const long long &j) { return a[i] > a[j]; });
  long long mn = get(2);
  cout << mx - mn << endl;
  return 0;
}
