#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
const int oo = 1e8 + 5;
struct edges {
  int x, y;
} e[maxn];
long long r[maxn];
int idx[maxn], n;
pair<int, int> stt[maxn], a[maxn];
vector<int> g[maxn];
long long mx, mn;
bool visited[maxn];
void prep() {
  for (int i = 1; i <= n; ++i) r[i] = -1;
}
int root(int x) {
  while (r[x] >= 0) x = r[x];
  return x;
}
void unite(int x, int y, int q, int tmp) {
  int xr = root(x), yr = root(y);
  if (xr == yr) return;
  if (q == 1)
    mx += r[xr] * r[yr] * tmp;
  else
    mn += r[xr] * r[yr] * tmp;
  if (r[xr] > r[yr]) swap(xr, yr);
  r[xr] += r[yr];
  r[yr] = xr;
}
void dsu(int u, int q, int tmp) {
  for (int j = 0; j < (int)g[u].size(); ++j) {
    int id = g[u][j];
    int v = e[id].y;
    if (v == u) v = e[id].x;
    if (root(u) != root(v)) {
      if (q * a[idx[u]].first >= q * a[idx[v]].first) {
        unite(u, v, q, a[idx[u]].first);
      }
    }
  }
}
void smax() {
  for (int i = 1; i <= n; ++i) idx[a[i].second] = i;
  for (int i = 1; i <= n; ++i) {
    int u = a[i].second;
    dsu(u, 1, a[i].first);
  }
}
void smin() {
  for (int i = 1; i <= n; ++i) idx[a[i].second] = i;
  for (int i = 1; i <= n; ++i) {
    int u = a[i].second;
    dsu(u, -1, a[i].first);
  }
}
void solve() {
  sort(a + 1, a + n + 1);
  smax();
  prep();
  reverse(a + 1, a + n + 1);
  smin();
  cout << mx - mn << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie();
  cout.tie();
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    int x;
    cin >> x;
    a[i] = pair<int, int>(x, i);
  }
  for (int i = 1; i <= n - 1; ++i) {
    cin >> e[i].x >> e[i].y;
    g[e[i].x].push_back(i);
    g[e[i].y].push_back(i);
  }
  prep();
  solve();
  return 0;
}
