#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const long long int N = 1000005;
vector<long long int> gr[N];
pair<long long int, long long int> a[N];
long long int n, vis[N];
struct dsu {
  vector<long long int> p, sz;
  long long int comp;
  dsu(long long int NN) {
    sz.clear();
    p.clear();
    p.resize(NN);
    sz.resize(NN, 1);
    iota(p.begin(), p.end(), 0);
    comp = NN;
  }
  long long int get(long long int x) {
    return (x == p[x] ? x : (p[x] = get(p[x])));
  }
  void unite(long long int x, long long int y) {
    x = get(x);
    y = get(y);
    if (sz[x] > sz[y]) {
      swap(x, y);
    }
    if (x != y) {
      p[x] = y;
      sz[y] += sz[x];
      sz[x] = 0;
      comp--;
    }
  }
};
long long int give_sum_of_max_of_all_paths() {
  long long int i, j, k, m, ans = 0, cnt = 0, sum = 0;
  dsu G(n);
  sort(a, a + n);
  memset(vis, 0, sizeof(vis));
  for (i = 0; i < n; i++) {
    long long int w = a[i].first;
    long long int cur = a[i].second;
    sum = 0;
    for (auto x : gr[cur]) {
      if (vis[x] == 0) continue;
      sum += G.sz[G.get(x)];
    }
    ans += (sum + 1) * w;
    for (auto x : gr[cur]) {
      if (vis[x] == 0) continue;
      sum -= G.sz[G.get(x)];
      ans += w * G.sz[G.get(x)] * sum;
      G.unite(cur, x);
    }
    vis[cur] = 1;
  }
  return ans;
}
void solve() {
  long long int i, j, k, m, ans = 0, cnt = 0, sum = 0;
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> a[i].first;
    a[i].second = i;
  }
  for (i = 0; i < n - 1; i++) {
    long long int x, y;
    cin >> x >> y;
    x--;
    y--;
    gr[x].push_back(y);
    gr[y].push_back(x);
  }
  ans = give_sum_of_max_of_all_paths();
  for (i = 0; i < n; i++) {
    a[i].first *= -1;
  }
  ans += give_sum_of_max_of_all_paths();
  cout << ans;
  return;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  solve();
  return 0;
}
