#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
ifstream in("test.in");
ofstream out("test.out");
const int DIM = 1000005;
int val[DIM], rot[DIM], oki[DIM];
pair<int, int> ord[DIM];
vector<int> edg[DIM];
inline int getRoot(int x) {
  while (rot[x] > 0) {
    x = rot[x];
  }
  return x;
}
long long solve(int n, int v) {
  for (int i = 1; i <= n; ++i) {
    ord[i] = make_pair(val[i] * v, i);
    rot[i] = -1;
    oki[i] = 0;
  }
  sort(ord + 1, ord + n + 1);
  long long ans = 0;
  for (int i = 1; i <= n; ++i) {
    int x = ord[i].second;
    oki[x] = true;
    vector<int> aux;
    for (int y : edg[x])
      if (oki[y]) {
        int r1 = getRoot(x), r2 = getRoot(y);
        aux.push_back(-rot[r2]);
        if (rot[r1] > rot[r2]) {
          swap(r1, r2);
        }
        if (r1 != r2) {
          rot[r1] += rot[r2];
          rot[r2] = r1;
        }
      }
    long long cnt = 1, psm = 0;
    for (int v : aux) {
      cnt += v + psm * v;
      psm += v;
    }
    ans += cnt * ord[i].first;
  }
  return ans;
}
int main(void) {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> val[i];
  }
  for (int i = 1; i < n; ++i) {
    int x, y;
    cin >> x >> y;
    edg[x].push_back(y);
    edg[y].push_back(x);
  }
  cout << solve(n, 1) + solve(n, -1);
  return 0;
}
