#include <bits/stdc++.h>
using namespace std;
const int N = 1000006;
int n, x, y, op[N], sz[N], b[N];
pair<int, int> a[N];
vector<int> v[N];
void R() {
  for (int i = 1; i <= n; ++i) {
    op[i] = i;
    sz[i] = 1;
  }
}
int P(int a) { return (op[a] == a ? a : op[a] = P(op[a])); }
void U(int a, int b) {
  sz[P(b)] += sz[P(a)];
  op[P(a)] = P(b);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i].first;
    a[i].second = i;
  }
  for (int i = 1; i < n; ++i) {
    cin >> x >> y;
    v[x].push_back(y);
    v[y].push_back(x);
  }
  R();
  sort(a + 1, a + n + 1);
  for (int i = 1; i <= n; ++i) {
    b[a[i].second] = i;
  }
  long long mx = 0;
  for (int i = 1; i <= n; ++i) {
    long long x = 0;
    for (int j = 0; j < v[a[i].second].size(); ++j) {
      if (a[b[v[a[i].second][j]]] < a[i]) {
        x += sz[P(v[a[i].second][j])];
      }
    }
    long long ap = 0;
    for (int j = 0; j < v[a[i].second].size(); ++j) {
      if (a[b[v[a[i].second][j]]] < a[i]) {
        ap += sz[P(v[a[i].second][j])] * (x - sz[P(v[a[i].second][j])]);
        U(v[a[i].second][j], a[i].second);
      }
    }
    ap = ap / 2 + x + 1;
    mx += ap * a[i].first;
  }
  for (int i = 1; i <= n; ++i) a[i].first = -a[i].first;
  R();
  sort(a + 1, a + n + 1);
  for (int i = 1; i <= n; ++i) {
    b[a[i].second] = i;
  }
  long long mn = 0;
  for (int i = 1; i <= n; ++i) {
    long long x = 0;
    for (int j = 0; j < v[a[i].second].size(); ++j) {
      if (a[b[v[a[i].second][j]]] < a[i]) {
        x += sz[P(v[a[i].second][j])];
      }
    }
    long long ap = 0;
    for (int j = 0; j < v[a[i].second].size(); ++j) {
      if (a[b[v[a[i].second][j]]] < a[i]) {
        ap += sz[P(v[a[i].second][j])] * (x - sz[P(v[a[i].second][j])]);
        U(v[a[i].second][j], a[i].second);
      }
    }
    ap = ap / 2 + x + 1;
    mn += ap * a[i].first;
  }
  cout << mx + mn << endl;
  return 0;
}
