#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int fa[N], sz[N];
vector<int> G[N];
pair<int, int> a[N];
void init() {
  for (int i = 1; i < N; i++) fa[i] = i, sz[i] = 1;
}
int find_fa(int u) { return fa[u] = (fa[u] == u ? u : find_fa(fa[u])); }
void unite(int u, int v) {
  u = find_fa(u);
  v = find_fa(v);
  fa[v] = u, sz[u] += sz[v];
}
int n;
bool vis[N];
long long calmax() {
  init();
  memset(vis, 0, sizeof(vis));
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    long long s = 0, cur = 0;
    int u = a[i].second;
    for (int j = 0; j < G[u].size(); j++) {
      int v = G[u][j];
      if (!vis[v]) continue;
      v = find_fa(v);
      s += sz[v], cur += 1LL * sz[v] * sz[v];
      unite(u, v);
    }
    cur = (s * s - cur) / 2 + s + 1;
    ans += cur * a[i].first;
    vis[a[i].second] = 1;
  }
  return ans;
}
long long calmin() {
  init();
  memset(vis, 0, sizeof(vis));
  long long ans = 0;
  for (int i = n; i >= 1; i--) {
    long long s = 0, cur = 0;
    int u = a[i].second;
    for (int j = 0; j < G[u].size(); j++) {
      int v = G[u][j];
      if (!vis[v]) continue;
      v = find_fa(v);
      s += sz[v], cur += 1LL * sz[v] * sz[v];
      unite(u, v);
    }
    cur = (s * s - cur) / 2 + s + 1;
    ans += cur * a[i].first;
    vis[a[i].second] = 1;
  }
  return ans;
}
void solve() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i].first), a[i].second = i;
  sort(a + 1, a + n + 1);
  for (int i = 1; i < n; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    G[u].push_back(v);
    G[v].push_back(u);
  }
  cout << calmax() - calmin() << endl;
}
int main() {
  solve();
  return 0;
}
