#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 100;
int sz[maxn];
int par[maxn];
pair<int, int> a[maxn];
bool mark[maxn];
vector<int> v[maxn];
int get(int x) {
  if (par[x] == 0) return x;
  return par[x] = get(par[x]);
}
void mrg(int x, int y) {
  x = get(x);
  y = get(y);
  if (x == y) return;
  sz[x] += sz[y];
  par[y] = x;
}
int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i].first;
    a[i].second = i;
    sz[i] = 1;
  }
  sort(a + 1, a + n + 1);
  reverse(a + 1, a + n + 1);
  for (int i = 1; i < n; i++) {
    int fi, se;
    cin >> fi >> se;
    v[fi].push_back(se);
    v[se].push_back(fi);
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    int x = a[i].second;
    mark[x] = true;
    for (int j = 0; j < v[x].size(); j++) {
      int child = v[x][j];
      if (!mark[child]) continue;
      if (get(x) != get(child)) {
        ans += 1ll * sz[get(child)] * sz[get(x)] * a[i].first;
        mrg(x, child);
      }
    }
  }
  for (int i = 1; i <= n; i++) {
    sz[i] = 1;
    par[i] = 0;
  }
  memset(mark, false, sizeof mark);
  long long ans1 = 0;
  for (int i = n; i >= 1; i--) {
    int x = a[i].second;
    mark[x] = true;
    for (int j = 0; j < v[x].size(); j++) {
      int child = v[x][j];
      if (!mark[child]) continue;
      if (get(x) != get(child)) {
        ans1 += 1ll * sz[get(child)] * sz[get(x)] * a[i].first;
        mrg(x, child);
      }
    }
  }
  cout << ans1 - ans << endl;
}
