#include <bits/stdc++.h>
using namespace std;
int read() {
  char c = getchar();
  int x = 0;
  while (c < '0' || c > '9') c = getchar();
  while (c >= '0' && c <= '9') x = x * 10 + (c - '0'), c = getchar();
  return x;
}
void MOD(int &x) {
  if (x >= 998244353) x -= 998244353;
}
int l, nxt[1000010 * 2], head[1000010], to[1000010 * 2];
void add(int x, int y) {
  l++;
  nxt[l] = head[x];
  head[x] = l;
  to[l] = y;
}
struct node {
  int v, id;
} a[1000010];
bool cmp(node a, node b) { return a.v < b.v; }
int u[1000010], sz[1000010], fa[1000010];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
int main() {
  int n;
  n = read();
  for (int i = 1; i <= n; i++) a[i].v = read(), a[i].id = i;
  for (int i = 1; i < n; i++) {
    int x, y;
    x = read();
    y = read();
    add(x, y);
    add(y, x);
  }
  sort(a + 1, a + n + 1, cmp);
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    int x = a[i].id;
    u[x] = 1;
    sz[x] = 1;
    fa[x] = x;
    for (int j = head[x]; j; j = nxt[j]) {
      int c = to[j];
      if (u[c]) {
        ans += 1ll * a[i].v * sz[find(x)] * sz[find(c)];
        sz[find(x)] += sz[find(c)], fa[find(c)] = find(x);
      }
    }
  }
  for (int i = 1; i <= n; i++) u[i] = 0;
  for (int i = n; i >= 1; i--) {
    int x = a[i].id;
    u[x] = 1;
    sz[x] = 1;
    fa[x] = x;
    for (int j = head[x]; j; j = nxt[j]) {
      int c = to[j];
      if (u[c]) {
        ans -= 1ll * a[i].v * sz[find(x)] * sz[find(c)];
        sz[find(x)] += sz[find(c)], fa[find(c)] = find(x);
      }
    }
  }
  printf("%lld\n", ans);
}
