#include <bits/stdc++.h>
using namespace std;
const long long int maxn = 1e6 + 5, M = 505, bghs = 1e9 + 7, inf = 1e18;
long long int n, cst[maxn], par[maxn];
bool mark[maxn];
vector<long long int> adj[maxn];
long long int ans = 0;
vector<pair<long long int, long long int> > v;
long long int gpc(long long int u) {
  return (par[u] < 0) ? u : par[u] = gpc(par[u]);
}
void calc() {
  v.clear();
  memset(par, -1, sizeof par);
  memset(mark, 0, sizeof mark);
  for (int i = 0; i < n; i++) v.push_back(make_pair(cst[i], i));
  sort(v.begin(), v.end());
  for (auto x : v) {
    long long int root = x.second;
    mark[root] = true;
    for (auto y : adj[root]) {
      if (!mark[y]) continue;
      long long int py = gpc(y), px = gpc(root);
      ans += par[py] * par[px] * cst[root];
      par[px] += par[py];
      par[py] = px;
    }
  }
  for (int i = 0; i < n; i++) cst[i] *= -1;
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) cin >> cst[i];
  for (int i = 0; i < n - 1; i++) {
    long long int u, v;
    cin >> u >> v;
    u--;
    v--;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  calc();
  calc();
  cout << ans << '\n';
}
