#include <bits/stdc++.h>
using namespace std;
inline void rd(int &x) {
  int y = 0;
  char c = getchar();
  while (c < '0' || c > '9') c = getchar();
  while (c >= '0' && c <= '9') y = y * 10 + (c ^ 48), c = getchar();
  x = y;
}
void pf(long long x) {
  if (x > 9) pf(x / 10);
  putchar(x % 10 + '0');
}
int head[1000005], fa[1000005], cnt = 0, sz[1000005];
bool vis[1000005];
struct qwq {
  int col, id;
  bool operator<(const qwq &x) const { return col < x.col; }
} a[1000005];
struct ed {
  int v, nxt;
} e[1000005 << 1];
void add(int u, int v) {
  e[++cnt] = (ed){v, head[u]}, head[u] = cnt;
  e[++cnt] = (ed){u, head[v]}, head[v] = cnt;
}
int find(int x) { return (fa[x] == x) ? x : fa[x] = find(fa[x]); }
int main() {
  int n, i, u, v, j;
  long long ans = 0;
  rd(n);
  for (i = 1; i <= n; ++i) rd(a[i].col), a[i].id = fa[i] = i, sz[i] = 1;
  for (i = 1; i < n; ++i) rd(u), rd(v), add(u, v);
  sort(a + 1, a + n + 1);
  for (i = 1; i <= n; ++i) {
    int x = a[i].id;
    for (j = head[x]; j; j = e[j].nxt) {
      int to = e[j].v, c = find(x), d = find(to);
      if (vis[to] && c != d) {
        fa[d] = c;
        ans += 1ll * a[i].col * 1ll * sz[c] * sz[d];
        sz[c] += sz[d];
      }
    }
    vis[x] = 1;
  }
  for (i = 1; i <= n; ++i) vis[i] = 0, fa[i] = i, sz[i] = 1;
  for (i = n; i >= 1; --i) {
    int x = a[i].id;
    for (j = head[x]; j; j = e[j].nxt) {
      int to = e[j].v, c = find(x), d = find(to);
      if (vis[to] && c != d) {
        fa[d] = c;
        ans -= 1ll * a[i].col * 1ll * sz[c] * sz[d];
        sz[c] += sz[d];
      }
    }
    vis[x] = 1;
  }
  printf("%lld", ans);
}
