#include <bits/stdc++.h>
const long long MAX_N = 1e6 + 100;
const long long MOD = 1e9 + 7;
using namespace std;
vector<int> g[MAX_N];
pair<int, int> ver[MAX_N];
int a[MAX_N];
int p[MAX_N];
long long s[MAX_N];
int n;
void cl() {
  for (int i = 1; i <= n; ++i) {
    p[i] = i;
    s[i] = 1;
  }
}
int parent(int u) {
  while (u != p[u]) p[u] = p[p[u]], u = p[u];
  return u;
}
void mrg(int u, int v) {
  if (s[u] < s[v]) swap(u, v);
  s[u] += s[v];
  s[v] = 0;
  p[v] = u;
}
long long solve(int d) {
  cl();
  long long ret = 0;
  for (int i = 1; i <= n; ++i) {
    int u = ver[i].second;
    long long w = ver[i].first;
    long long paths = 0;
    int pr = parent(u);
    for (auto x : g[u]) {
      if ((d == 0 and a[x] > w) or (d == 1 and a[x] < w)) continue;
      int px = parent(x);
      if (px == pr) continue;
      paths += s[px] * s[pr];
      mrg(pr, px);
      pr = p[pr];
    }
    ret += w * paths;
  }
  return ret;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
  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);
  }
  for (int i = 1; i <= n; ++i) ver[i].first = a[i], ver[i].second = i;
  long long ans = 0;
  sort(ver + 1, ver + n + 1);
  ans = solve(0);
  reverse(ver + 1, ver + n + 1);
  cout << (ans - solve(1));
  return 0;
}
