#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int MAXN = 1e6 + 100;
vector<int> g[MAXN];
int par[MAXN], depth[MAXN], n;
long long ok[MAXN];
pair<long long, long long> aa[MAXN];
bool mark[MAXN];
int find(int v) {
  if (v == par[v]) return v;
  return par[v] = find(par[v]);
}
void merge(int a, int b) {
  a = find(a);
  b = find(b);
  if (a == b) return;
  depth[a] += depth[b];
  par[b] = a;
}
long long check() {
  for (int i = 1; i < n + 1; i++) {
    mark[i] = 0;
    par[i] = i;
    depth[i] = 1;
  }
  long long an = 0;
  for (int i = 1; i < n + 1; i++) aa[i] = {ok[i], i};
  sort(aa + 1, aa + n + 1);
  for (int i = 1; i < n + 1; i++) {
    int kk = aa[i].second;
    an += ok[kk];
    long long check = 1;
    for (auto it : g[kk]) {
      if (!mark[it]) continue;
      an += check * depth[find(it)] * ok[kk];
      check += depth[find(it)];
      merge(kk, it);
    }
    mark[kk] = 1;
  }
  return an;
}
void solve() {
  cin >> n;
  for (int i = 1; i < n + 1; i++) cin >> ok[i];
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  long long kiosk = check();
  for (int i = 1; i < n + 1; i++) ok[i] = -ok[i];
  kiosk += check();
  cout << kiosk << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int t = 1;
  while (t--) {
    solve();
  }
  cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
  return 0;
}
