#include <bits/stdc++.h>
using namespace std;
template <typename T, typename L>
bool smax(T& x, L y) {
  return x < y ? (x = y, true) : false;
}
template <typename T, typename L>
bool smin(T& x, L y) {
  return y < x ? (x = y, true) : false;
}
void prep(long long* mem);
void reset();
int root(int v);
const int MAXN = 1e6 + 15;
int par[MAXN];
int sz[MAXN];
int val[MAXN];
int id[MAXN];
bool mark[MAXN];
long long d[2][MAXN];
int n;
long long ans;
vector<int> adj[MAXN];
int main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  cin >> n;
  for (int i = 0; i < n; i++) cin >> val[i];
  for (int i = 1, u, v; i < n; i++) {
    cin >> u >> v;
    u--, v--;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  prep(d[0]);
  for (int i = 0; i < n; val[i++] *= -1)
    ;
  prep(d[1]);
  for (int i = 0; i < n; i++)
    ans += ((long long)(*(d[0] + i) - *(d[1] + i)) * (long long)(-*(val + i)));
  return cout << ans << '\n', false;
}
void prep(long long* mem) {
  reset();
  for (int j = 0; j < n; j++) {
    int i = id[j];
    mark[i] = true;
    for (auto u : adj[i]) {
      if (!mark[u]) continue;
      int k = root(u);
      mem[i] += ((long long)sz[i] * (long long)sz[k]);
      par[k] = i;
      sz[i] += sz[k];
      sz[k] = 0;
    }
  }
}
int root(int v) { return (par[v] == v ? v : par[v] = root(par[v])); }
void reset() {
  iota(id, id + n, 0);
  sort(id, id + n, [](int x, int y) { return val[x] < val[y]; });
  memset(mark, false, sizeof mark);
  for (int i = 0; i < n; sz[i] = 1, par[i] = i, i++)
    ;
}
