#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const long double eps = 1e-7;
const int inf = 1000000010;
const long long INF = 10000000000010LL;
const int mod = 1000000007;
const int MAXN = 1000010;
long long n, m, u, v, x, y, t, a, b, ans;
long long A[MAXN];
int ind[MAXN];
int par[MAXN];
long long sz[MAXN];
bool mark[MAXN];
vector<int> G[MAXN];
bool cmp(int i, int j) { return A[i] < A[j]; }
int get(int x) {
  if (par[x] == x) return x;
  return par[x] = get(par[x]);
}
int main() {
  ios_base::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; i < n - 1; i++) {
    cin >> x >> y;
    G[x].push_back(y);
    G[y].push_back(x);
  }
  for (int i = 1; i < MAXN; i++) par[i] = i;
  for (int i = 1; i < MAXN; i++) ind[i] = i;
  sort(ind + 1, ind + n + 1, cmp);
  for (int j = 1; j <= n; j++) {
    int i = ind[j];
    long long s = 0;
    long long tmp = 0;
    for (int v : G[i]) {
      int x = get(v);
      if (!mark[v]) continue;
      par[x] = i;
      s += sz[x];
      ans += sz[x] * A[i];
      tmp += sz[x] * sz[x];
    }
    ans += (s * s - tmp) / 2 * A[i];
    sz[i] = s + 1;
    mark[i] = true;
  }
  cerr << "ans" << '=' << ans << endl;
  ;
  reverse(ind + 1, ind + n + 1);
  memset(mark, 0, sizeof(mark));
  memset(sz, 0, sizeof(sz));
  for (int i = 1; i < MAXN; i++) par[i] = i;
  for (int j = 1; j <= n; j++) {
    int i = ind[j];
    long long s = 0, tmp = 0;
    for (int v : G[i]) {
      int x = get(v);
      if (!mark[v]) continue;
      par[x] = i;
      s += sz[x];
      ans -= sz[x] * A[i];
      tmp += sz[x] * sz[x];
    }
    ans -= (s * s - tmp) / 2 * A[i];
    sz[i] = s + 1;
    mark[i] = true;
  }
  cout << ans << endl;
  return 0;
}
