#include <bits/stdc++.h>
using namespace std;
const long long MAX = 1e6 + 7;
vector<long long> Nxt[MAX];
vector<long long> val[MAX];
long long N;
struct node {
  long long father, size, pathCnt, maxVal;
  node(long long f = 0, long long s = 0, long long p = 0, long long m = 0) {
    father = f;
    size = s;
    pathCnt = p, maxVal = m;
  }
};
bool vis[MAX];
long long tool[MAX];
node F[MAX];
node find(long long x) {
  return (F[x].father == x) ? F[x] : F[x] = find(F[x].father);
}
void add(long long x, long long v) {
  F[x] = node(x, 1, 0, v);
  for (long long i = 0; i < Nxt[x].size(); i++) {
    long long xx = Nxt[x][i];
    if (!vis[xx]) continue;
    node n = find(xx);
    F[x].size += n.size;
    if (n.maxVal != v)
      F[x].pathCnt += (n.size * n.size);
    else
      F[x].pathCnt += n.pathCnt;
    F[n.father].father = x;
  }
  vis[x] = 1;
}
long long Sum(long long from, long long to, long long step) {
  long long ans = 0;
  memset(vis, 0, sizeof(vis));
  memset(tool, 0, sizeof(tool));
  long long i, j;
  for (i = from; i != to; i += step) {
    if (val[i].size()) {
      long long s = val[i].size();
      for (j = 0; j < s; j++) {
        add(val[i][j], i);
      }
      for (j = 0; j < s; j++) {
        node x = find(val[i][j]);
        if (tool[x.father]) continue;
        tool[x.father] = 1;
        long long newPath = x.size * x.size - x.pathCnt;
        ans += i * newPath;
      }
    }
  }
  return ans;
}
int main() {
  scanf("%lld", &N);
  long long i;
  for (i = 1; i <= N; i++) {
    long long x;
    scanf("%lld", &x);
    val[x].push_back(i);
  }
  for (i = 1; i < N; i++) {
    long long x, y;
    scanf("%lld%lld", &x, &y);
    Nxt[x].push_back(y);
    Nxt[y].push_back(x);
  }
  long long ans = Sum(0, MAX - 1, 1) - Sum(MAX - 1, 0, -1);
  cout << (ans >> 1);
  return 0;
}
