#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
struct node {
  int id, w;
};
vector<int> edge[maxn];
int fa[maxn], a[maxn], vis[maxn], siz[maxn], n, m;
node p[maxn];
bool cmp1(node a1, node a2) { return a1.w < a2.w; }
bool cmp2(node a1, node a2) { return a1.w > a2.w; }
int find(int u) { return fa[u] == u ? u : fa[u] = find(fa[u]); }
void reset() {
  for (int i = 1; i <= n; i++) fa[i] = i, siz[i] = 1, vis[i] = 0;
}
int main() {
  int i, j, k;
  int u, v;
  scanf("%d", &n);
  for (i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    p[i].id = i;
    p[i].w = a[i];
  }
  for (i = 1; i < n; i++) {
    scanf("%d%d", &u, &v);
    edge[u].push_back(v);
    edge[v].push_back(u);
  }
  long long ans = 0;
  reset();
  sort(p + 1, p + 1 + n, cmp1);
  for (i = 1; i <= n; i++) {
    vector<int> vec;
    node e = p[i];
    int u = e.id;
    vis[u] = 1;
    for (int i = 0; i < edge[u].size(); i++) {
      int v = edge[u][i];
      if (vis[v]) {
        int f = find(v);
        vec.push_back(siz[f]);
        fa[f] = u;
        siz[u] += siz[f];
      }
    }
    int sm = siz[u];
    for (int i = 0; i < vec.size(); i++) {
      ans += a[u] * (long long)vec[i] * (sm - vec[i]);
      sm -= vec[i];
    }
  }
  reset();
  sort(p + 1, p + 1 + n, cmp2);
  for (i = 1; i <= n; i++) {
    vector<int> vec;
    node e = p[i];
    int u = e.id;
    vis[u] = 1;
    for (int i = 0; i < edge[u].size(); i++) {
      int v = edge[u][i];
      if (vis[v]) {
        int f = find(v);
        vec.push_back(siz[f]);
        fa[f] = u;
        siz[u] += siz[f];
      }
    }
    int sm = siz[u];
    for (int i = 0; i < vec.size(); i++) {
      ans -= a[u] * (long long)vec[i] * (sm - vec[i]);
      sm -= vec[i];
    }
  }
  cout << ans;
  return 0;
}
