#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int n, fa[N], sz[N], a[N], id[N];
int cnt = 0, hed[N], to[N + N], nxt[N + N];
bool used[N];
long long ans = 0;
inline bool cmp(const int &x, const int &y) { return a[x] < a[y]; }
inline void add(int x, int y) {
  to[++cnt] = y, nxt[cnt] = hed[x], hed[x] = cnt;
}
int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
void Union(int x, int y) {
  x = find(x), y = find(y);
  if (x == y) return;
  if (sz[x] > sz[y]) swap(x, y);
  fa[x] = y, sz[y] += sz[x];
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]), id[i] = i;
  sort(id + 1, id + n + 1, cmp);
  for (int i = 1, x, y; i < n; i++) scanf("%d%d", &x, &y), add(x, y), add(y, x);
  for (int i = 1; i <= n; i++) fa[i] = i, sz[i] = 1, used[i] = 0;
  for (int i = 1, u; i <= n; i++) {
    u = id[i], used[u] = 1;
    int sum;
    for (int j = hed[u]; j; j = nxt[j]) {
      if (!used[to[j]]) continue;
      sum = sz[find(u)];
      ans += (long long)sum * sz[find(to[j])] * a[u], Union(to[j], u);
    }
  }
  for (int i = 1; i <= n; i++) fa[i] = i, sz[i] = 1, used[i] = 0;
  for (int i = n, u; i; i--) {
    u = id[i], used[u] = 1;
    int sum;
    for (int j = hed[u]; j; j = nxt[j]) {
      if (!used[to[j]]) continue;
      sum = sz[find(u)];
      ans -= (long long)sum * sz[find(to[j])] * a[u], Union(to[j], u);
    }
  }
  printf("%I64d\n", ans);
  return 0;
}
