#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e6 + 7;
int n, mk[MAX], dsu[MAX], csz[MAX];
vector<int> g[MAX];
vector<pair<int, int> > v;
inline void init() {
  for (int i = (1); i <= (n); ++i) {
    dsu[i] = i, csz[i] = 1;
  }
}
inline int get(int u) { return dsu[u] == u ? u : dsu[u] = get(dsu[u]); }
void join(int u, int v) {
  int x = get(u), y = get(v);
  if (x == y) return;
  dsu[x] = y;
  csz[y] += csz[x];
}
long long int solve() {
  long long int r = 0ll;
  fill(mk, mk + n + 1, 0);
  init();
  for (int i = (0); i <= (n - 1); ++i) {
    int nd = v[i].second;
    mk[nd] = 1;
    long long int act = 1ll;
    for (auto nn : g[nd]) {
      if (!mk[nn]) continue;
      act += 1ll * csz[get(nd)] * csz[get(nn)];
      join(nd, nn);
    }
    r += act * v[i].first;
  }
  return r;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = (1); i <= (n); ++i) {
    int c;
    cin >> c;
    v.emplace_back((make_pair((c), (i))));
  }
  for (int i = (1); i <= (n - 1); ++i) {
    int x, y;
    cin >> x >> y;
    g[y].emplace_back((x));
    g[x].emplace_back((y));
  }
  long long int ans = 0ll;
  sort((v).begin(), (v).end());
  ans += solve();
  reverse((v).begin(), (v).end());
  ans -= solve();
  cout << ans << '\n';
  return 0;
}
