#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000000;
int a[maxn + 5], f[maxn + 5], sz[maxn + 5];
vector<int> g[maxn + 5];
int pos[maxn + 5];
long long s;
int n;
bool cmp(const int x, const int y) { return a[x] < a[y]; }
bool cmp1(const int x, const int y) { return a[x] > a[y]; }
int find(int x) {
  if (f[x] == x)
    return x;
  else
    return f[x] = find(f[x]);
}
void merge(int x, int y, int value) {
  if (!f[x] || !f[y]) return;
  x = find(x), y = find(y);
  s += 1LL * sz[x] * sz[y] * value;
  f[x] = y;
  sz[y] += sz[x];
}
long long solve() {
  for (int i = 0; i <= n; ++i) f[i] = 0, sz[i] = 0;
  s = 0;
  for (int i = 1; i <= n; ++i) {
    int x = pos[i];
    f[x] = x, sz[x] = 1;
    for (int j = 0; j < g[x].size(); ++j) merge(x, g[x][j], a[x]);
  }
  return s;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
  for (int i = 1; i < n; ++i) {
    int u, v;
    scanf("%d%d", &u, &v);
    g[u].push_back(v);
    g[v].push_back(u);
  }
  for (int i = 1; i <= n; ++i) pos[i] = i;
  sort(pos + 1, pos + n + 1, cmp);
  long long ans1 = solve();
  sort(pos + 1, pos + n + 1, cmp1);
  long long ans2 = solve();
  printf("%lld\n", ans1 - ans2);
  return 0;
}
