#include <bits/stdc++.h>
using namespace std;
const int MX = 1e6 + 10;
int n, m, a[MX], u, v, par[MX][2];
long long mn, ans, sz[MX][2];
vector<int> adj[MX];
pair<int, pair<int, int> > min_edge[MX], max_edge[MX];
int parent(int node, int mode) {
  if (par[node][mode] == node) return node;
  return (par[node][mode] = parent(par[node][mode], mode));
}
int dsu(int u, int v, int num, int mode) {
  u = parent(u, mode);
  v = parent(v, mode);
  if (adj[u].size() < adj[v].size()) {
    swap(u, v);
  }
  mn += sz[u][mode] * sz[v][mode] * num;
  sz[u][mode] += sz[v][mode];
  par[v][mode] = u;
  return (0);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 1; i <= n - 1; i++) {
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
    min_edge[i] = {min(a[u], a[v]), {u, v}};
    max_edge[i] = {max(a[u], a[v]), {u, v}};
  }
  sort(min_edge, min_edge + n);
  reverse(min_edge, min_edge + n + 1);
  sort(max_edge, max_edge + n);
  for (int i = 1; i <= n; i++) {
    par[i][0] = i;
    par[i][1] = i;
    sz[i][0] = 1;
    sz[i][1] = 1;
  }
  for (int i = 1; i <= n - 1; i++) {
    if (parent(max_edge[i].second.first, 0) !=
        parent(max_edge[i].second.second, 0)) {
      dsu(max_edge[i].second.first, max_edge[i].second.second,
          max_edge[i].first, 0);
    }
  }
  ans = mn;
  mn = 0;
  for (int i = 1; i <= n - 1; i++) {
    if (parent(min_edge[i].second.first, 1) !=
        parent(min_edge[i].second.second, 1)) {
      dsu(min_edge[i].second.first, min_edge[i].second.second,
          min_edge[i].first, 1);
    }
  }
  ans = ans - mn;
  cout << ans << endl;
}
