#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int INF = INT_MAX;
const long long LINF = LLONG_MAX;
const int N = 1e6 + 20;
vector<pair<int, pair<int, int> > > mi, mx;
long long n, a[N], f, g, dsu[N];
long long find(int x) { return dsu[x] < 0 ? x : (dsu[x] = find(dsu[x])); }
void merge(int x, int y) {
  if ((x = find(x)) == (y = find(y))) return;
  if (dsu[y] < dsu[x]) swap(x, y);
  dsu[x] += dsu[y];
  dsu[y] = x;
}
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];
  for (int i = 0, v, u; i < n - 1; i++) {
    cin >> v >> u;
    mx.push_back(make_pair(max(a[v], a[u]), make_pair(v, u)));
    mi.push_back(make_pair(min(a[v], a[u]), make_pair(v, u)));
  }
  sort(mx.begin(), mx.end());
  sort(mi.begin(), mi.end());
  memset(dsu, -1, sizeof dsu);
  for (int i = 0; i < n - 1; i++)
    f += dsu[find(mx[i].second.first)] * dsu[find(mx[i].second.second)] *
         mx[i].first,
        merge(mx[i].second.first, mx[i].second.second);
  memset(dsu, -1, sizeof dsu);
  for (int i = n - 2; i >= 0; i--)
    g += dsu[find(mi[i].second.first)] * dsu[find(mi[i].second.second)] *
         mi[i].first,
        merge(mi[i].second.first, mi[i].second.second);
  cout << f - g << endl;
}
