#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
long long mn, mx, ans;
vector<int> adj[N];
int n, a[N], par_sz[N];
vector<pair<int, int> > ve;
int get_par(int u) {
  return par_sz[u] >= 0 ? par_sz[u] = get_par(par_sz[u]) : u;
}
long long merge(int u, int v) {
  u = get_par(u), v = get_par(v);
  if (u == v) return 0;
  long long res = 1LL * par_sz[v] * par_sz[u];
  if (par_sz[u] > par_sz[v]) swap(u, v);
  par_sz[u] += par_sz[v];
  par_sz[v] = u;
  return res;
}
void input() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    ve.push_back(make_pair(a[i], i));
  }
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    u--, v--;
    adj[u].push_back(v), adj[v].push_back(u);
  }
}
long long find_mx() {
  memset(par_sz, -1, sizeof par_sz);
  for (int i = 0; i < ve.size(); i++) {
    int v = ve[i].second, w = ve[i].first;
    for (int j = 0; j < adj[v].size(); j++) {
      int u = adj[v][j];
      if (a[u] <= w) mx += 1LL * w * merge(u, v);
    }
  }
  return mx;
}
long long find_mn() {
  memset(par_sz, -1, sizeof par_sz);
  for (int i = ve.size() - 1; i >= 0; i--) {
    int v = ve[i].second, w = ve[i].first;
    for (int j = 0; j < adj[v].size(); j++) {
      int u = adj[v][j];
      if (a[u] >= w) mn -= 1LL * w * merge(u, v);
    }
  }
  return mn;
}
void solve() {
  sort(ve.begin(), ve.end());
  ans = find_mx() + find_mn();
}
void output() { cout << ans << '\n'; }
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  input(), solve(), output();
  return 0;
}
