#include <bits/stdc++.h>
using namespace std;
int dsu[1234567], a[1234567];
vector<vector<int> > adj(1234567);
int paren(int u) {
  if (dsu[u] < 0) return u;
  dsu[u] = paren(dsu[u]);
  return dsu[u];
}
long long ans = 0, value = 0;
int merge(int u, int v) {
  u = paren(u);
  v = paren(v);
  if (u == v) return 0;
  ans += value * dsu[u] * dsu[v];
  if (dsu[u] < dsu[v]) {
    swap(u, v);
  }
  dsu[v] += dsu[u];
  dsu[u] = v;
  return 0;
}
vector<pair<long long, long long> > vec;
int main() {
  std::ios::sync_with_stdio(false);
  int n;
  cin >> n;
  int i, j, u, v;
  for (i = 0; i < n; i++) {
    cin >> a[i];
    vec.push_back(make_pair(a[i], i));
    dsu[i] = -1;
  }
  sort(vec.begin(), vec.end());
  for (i = 0; i < n - 1; i++) {
    cin >> u >> v;
    u--;
    v--;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  int cur;
  for (i = 0; i < vec.size(); i++) {
    value = vec[i].first;
    cur = vec[i].second;
    for (j = 0; j < adj[cur].size(); j++) {
      if (a[adj[cur][j]] <= a[cur]) {
        merge(cur, adj[cur][j]);
      }
    }
  }
  long long addo = ans;
  for (i = 0; i < n; i++) {
    dsu[i] = -1;
  }
  ans = 0;
  for (i = vec.size() - 1; i >= 0; i--) {
    value = vec[i].first;
    cur = vec[i].second;
    for (j = 0; j < adj[cur].size(); j++) {
      if (a[adj[cur][j]] >= a[cur]) {
        merge(cur, adj[cur][j]);
      }
    }
  }
  cout << addo - ans << endl;
  return 0;
}
