#include <bits/stdc++.h>
using namespace std;
constexpr int MAXN = 1e6 + 14;
constexpr int MAXQ = 5e5 + 15;
constexpr int MOD = 1e9 + 7;
constexpr long long INF = 9187201950435737471;
constexpr int LOG = 35;
struct node {
  int u, v;
  void Get() { cin >> u >> v; }
};
long long n, a[MAXN], par[MAXN], ans;
node e[MAXN];
vector<int> G[MAXN], V;
bool cmp(int u, int v) { return a[u] < a[v]; }
int get_par(int u) { return (par[u] < 0 ? u : par[u] = get_par(par[u])); }
void merge(int u, int v, long long x) {
  if ((u = get_par(u)) == (v = get_par(v))) {
    return;
  }
  if (par[u] > par[v]) {
    swap(u, v);
  }
  ans += (-par[u]) * (-par[v]) * x;
  par[u] += par[v];
  par[v] = u;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    V.push_back(i);
  }
  for (int i = 1; i < n; i++) {
    e[i].Get();
    G[e[i].u].push_back(e[i].v);
    G[e[i].v].push_back(e[i].u);
  }
  sort(V.begin(), V.end(), cmp);
  memset(par, -1, sizeof par);
  for (auto u : V) {
    for (auto v : G[u]) {
      if (a[u] >= a[v]) {
        merge(u, v, a[u]);
      }
    }
  }
  memset(par, -1, sizeof par);
  reverse(V.begin(), V.end());
  for (auto u : V) {
    for (auto v : G[u]) {
      if (a[u] <= a[v]) {
        merge(u, v, -a[u]);
      }
    }
  }
  cout << ans;
  return 0;
}
