#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
long long power(long long a, long long b, long long mod) {
  long long c = 1;
  while (b > 0) {
    if (b % 2) c *= a, c %= mod;
    b /= 2;
    a *= a;
    a %= mod;
  }
  return c;
}
const long long N = (1e6) + 10;
const long long M = 320;
const long long Mod = 1e9 + 7;
long long par[N], s[N], vis[N];
pair<long long, long long> ar[N];
vector<long long> adj[N];
long long baap(long long f) {
  if (par[f] == f) return f;
  return par[f] = baap(par[f]);
}
void merge(long long a, long long b) {
  long long pa, push_back;
  pa = baap(a);
  push_back = baap(b);
  if (s[pa] > s[push_back]) swap(pa, push_back);
  par[pa] = push_back;
  s[push_back] += s[pa];
}
long long go(long long n) {
  long long i, j, k;
  sort(ar, ar + n);
  for (i = 0; i < n; i++) par[i] = i, s[i] = 1, vis[i] = 0;
  long long ans = 0;
  for (i = 0; i < n; i++) {
    long long cnt = 0;
    vector<long long> v;
    j = ar[i].second;
    vis[j] = 1;
    v.push_back(s[baap(j)]);
    for (auto z : adj[j]) {
      if (vis[z] == 0) continue;
      if (baap(z) == baap(j)) continue;
      v.push_back(s[baap(z)]);
      merge(z, j);
    }
    k = 0;
    for (auto z : v) k += z;
    j = 0;
    for (auto z : v) j += z * (k - z);
    j /= 2;
    ans += ar[i].first * j;
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cout << setprecision(25);
  long long n, m, b, c, d, i, j, k;
  cin >> n;
  for (i = 0; i < n; i++) cin >> ar[i].first, ar[i].second = i;
  for (i = 0; i < n - 1; i++)
    cin >> b >> c, b--, c--, adj[b].push_back(c), adj[c].push_back(b);
  b = go(n);
  for (i = 0; i < n; i++) ar[i].first *= -1;
  b += go(n);
  cout << b << '\n';
  return 0;
}
