#include <bits/stdc++.h>
using namespace std;
int sz[1000009];
int parent[1000009];
int a[1000009];
bool vis[1000009] = {false};
int pos[1000009];
vector<int> adj[1000009];
void make_set(int i) {
  sz[i] = 1;
  parent[i] = i;
  return;
}
int find_parent(int i) {
  if (parent[i] == i) return i;
  return parent[i] = find_parent(parent[i]);
}
int find_size(int i) {
  if (parent[i] == i) return sz[i];
  return find_size(parent[i]);
}
void merge(int x, int y) {
  x = find_parent(x);
  y = find_parent(y);
  if (sz[x] > sz[y]) swap(x, y);
  parent[x] = y;
  sz[y] += sz[x];
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) pos[i] = i;
  sort(pos + 1, pos + n + 1, [&](int i, int j) { return a[i] < a[j]; });
  int u, v;
  for (int i = 1; i < n; i++) {
    cin >> u >> v;
    adj[v].push_back(u);
    adj[u].push_back(v);
  }
  for (int i = 1; i <= n; i++) make_set(i);
  long long int maxx = 0;
  for (int i = 1; i <= n; i++) {
    long long int val = 0;
    long long int pref = 0;
    int x = pos[i];
    for (int y : adj[x]) {
      if (vis[y]) {
        int c = find_size(y);
        val += pref * c;
        val += c;
        pref += c;
      }
    }
    for (int y : adj[x])
      if (vis[y]) merge(x, y);
    val++;
    maxx += a[x] * val;
    vis[x] = true;
  }
  fill(vis + 1, vis + n + 1, false);
  for (int i = 1; i <= n; i++) make_set(i);
  long long int minn = 0;
  for (int i = n; i >= 1; i--) {
    long long int val = 0;
    long long int pref = 0;
    int x = pos[i];
    for (int y : adj[x]) {
      if (vis[y]) {
        int c = find_size(y);
        val += pref * c;
        val += c;
        pref += c;
      }
    }
    for (int y : adj[x])
      if (vis[y]) merge(x, y);
    val++;
    minn += a[x] * val;
    vis[x] = true;
  }
  cout << maxx - minn;
}
