#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int a[maxn];
vector<int> g[maxn];
int od[maxn], fa[maxn], sz[maxn];
int n;
bool less2(int x, int y) { return a[x] < a[y]; }
bool less3(int x, int y) { return a[x] > a[y]; }
inline int getfa(int x) { return fa[x] == x ? x : fa[x] = getfa(fa[x]); }
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);
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) od[i] = i, fa[i] = i, sz[i] = 1;
  sort(od + 1, od + 1 + n, less2);
  for (int _ = 1; _ <= n; _++) {
    int i = od[_];
    int uu = getfa(i);
    for (int j = 0; j < g[i].size(); j++) {
      int to = g[i][j];
      if (a[to] > a[i] || (a[to] == a[i] && to > i)) continue;
      int vv = getfa(g[i][j]);
      if (uu != vv) {
        fa[vv] = uu;
        ans += a[i] * 1ll * sz[uu] * sz[vv];
        sz[uu] += sz[vv];
      }
    }
  }
  for (int i = 1; i <= n; i++) od[i] = i, fa[i] = i, sz[i] = 1;
  sort(od + 1, od + 1 + n, less3);
  for (int _ = 1; _ <= n; _++) {
    int i = od[_];
    int uu = getfa(i);
    for (int j = 0; j < g[i].size(); j++) {
      int to = g[i][j];
      if (a[to] < a[i] || (a[to] == a[i] && to < i)) continue;
      int vv = getfa(g[i][j]);
      if (uu != vv) {
        fa[vv] = uu;
        ans -= a[i] * 1ll * sz[uu] * sz[vv];
        sz[uu] += sz[vv];
      }
    }
  }
  printf("%I64d\n", ans);
  return 0;
}
