#include <bits/stdc++.h>
using namespace std;
const long long int N = 2e6;
long long int n;
vector<long long int> v[N + 1];
long long int par[N + 1], arr[N + 1], b[N + 1], vis[N + 1], sz[N + 1];
long long int root(long long int node) {
  if (par[node] == node) return node;
  return par[node] = root(par[node]);
}
void ini() {
  for (long long int i = 1; i <= n; i++) {
    par[i] = i;
    sz[i] = 1;
    vis[i] = 0;
  }
}
bool cmp(long long int i, long long int j) { return arr[i] < arr[j]; }
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long int i = 1; i <= n; i++) {
    cin >> arr[i];
    b[i] = i;
  }
  sort(b + 1, b + n + 1, cmp);
  for (long long int i = 1; i <= n - 1; i++) {
    long long int a, b;
    cin >> a >> b;
    v[a].push_back(b);
    v[b].push_back(a);
  }
  ini();
  long long int ans = 0;
  for (long long int i = 1; i <= n; i++) {
    long long int x = b[i];
    vis[x] = 1;
    long long int ans1 = 0, ans2 = 0;
    for (auto j : v[x]) {
      if (vis[j]) {
        ans1 += sz[root(j)];
        ans2 += sz[root(j)] * sz[root(j)];
        sz[x] += sz[root(j)];
        par[root(j)] = x;
      }
    }
    ans += (ans1 + 1) * arr[x];
    ans += ((ans1 * ans1 - ans2) / 2) * arr[x];
  }
  ini();
  for (long long int i = n; i >= 1; i--) {
    long long int x = b[i];
    vis[x] = 1;
    long long int ans1 = 0, ans2 = 0;
    for (auto j : v[x]) {
      if (vis[j]) {
        ans1 += sz[root(j)];
        ans2 += sz[root(j)] * sz[root(j)];
        sz[x] += sz[root(j)];
        par[root(j)] = x;
      }
    }
    ans -= (ans1 + 1) * arr[x];
    ans -= ((ans1 * ans1 - ans2) / 2) * arr[x];
  }
  cout << ans << endl;
}
