#include <bits/stdc++.h>
using namespace std;
inline long long getnum() {
  char c = getchar();
  long long num, sign = 1;
  for (; c < '0' || c > '9'; c = getchar())
    if (c == '-') sign = -1;
  for (num = 0; c >= '0' && c <= '9';) {
    c -= '0';
    num = num * 10 + c;
    c = getchar();
  }
  return num * sign;
}
int par[1000004];
int ranku[1000004];
int cnt[1000004];
int find(int x) {
  if (par[x] == x) return x;
  return par[x] = find(par[x]);
}
int unite(int x, int y) {
  int xx = find(x);
  int yy = find(y);
  if (xx == yy) return 0;
  int boss;
  if (ranku[xx] < ranku[yy])
    par[xx] = yy, cnt[yy] += cnt[xx], boss = yy;
  else if (ranku[xx] > ranku[yy])
    par[yy] = xx, cnt[xx] += cnt[yy], boss = xx;
  else {
    cnt[xx] += cnt[yy];
    par[yy] = xx;
    ranku[xx]++;
    boss = xx;
  }
  return boss;
}
int A[1000006];
int vis[1000006];
pair<int, int> P[1000006];
vector<int> V[1000006];
int main() {
  int n = getnum();
  for (int i = 1; i <= n; i++) par[i] = i, cnt[i] = 1;
  for (int i = 1; i <= n; i++) A[i] = getnum(), P[i] = make_pair(A[i], i);
  sort(P + 1, P + n + 1);
  for (int i = 1; i < n; i++) {
    int x = getnum(), y = getnum();
    V[x].push_back(y);
    V[y].push_back(x);
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    int v = P[i].second;
    long long tot = 0;
    for (int j = 0; j < V[v].size(); j++) {
      int u = find(V[v][j]);
      if (A[u] > A[v]) continue;
      if ((A[u] == A[v] && vis[u]) || A[v] > A[u]) {
        tot += cnt[u];
        ans += (long long)A[v] * cnt[u] * (tot - cnt[u]);
      }
    }
    ans += (long long)A[v] * tot;
    for (int j = 0; j < V[v].size(); j++) {
      int u = find(V[v][j]);
      if (A[u] > A[v]) continue;
      if ((A[u] == A[v] && vis[u]) || A[v] > A[u]) unite(u, v);
    }
    vis[v] = 1;
  }
  for (int i = 1; i <= n; i++) par[i] = i, cnt[i] = 1, vis[i] = 0;
  for (int i = n; i >= 1; i--) {
    int v = P[i].second;
    long long tot = 0;
    for (int j = 0; j < V[v].size(); j++) {
      int u = find(V[v][j]);
      if (A[u] < A[v]) continue;
      if ((A[u] == A[v] && vis[u]) || A[v] < A[u]) {
        tot += cnt[u];
        ans -= (long long)A[v] * cnt[u] * (tot - cnt[u]);
      }
    }
    ans -= (long long)A[v] * tot;
    for (int j = 0; j < V[v].size(); j++) {
      int u = find(V[v][j]);
      if (A[u] < A[v]) continue;
      if ((A[u] == A[v] && vis[u]) || A[v] < A[u]) unite(u, v);
    }
    vis[v] = 1;
  }
  cout << ans << endl;
}
