#include <bits/stdc++.h>
using namespace std;
int n;
long long val[1000009], sz[1000009], ord[1000009];
int rep[1000009], in[1000009];
vector<int> v[1000009];
bool cmp(int x, int y) { return val[x] < val[y]; }
void bld() {
  for (int i = 0; i < n; i++) {
    rep[i] = i;
    sz[i] = 1;
    in[i] = 0;
  }
}
long long o = 1;
long long ans;
int fnd(int x) {
  if (x == rep[x]) return x;
  rep[x] = fnd(rep[x]);
  return rep[x];
}
void solve() {
  for (int i = 0; i < n; i++) {
    int x = ord[i];
    long long sm = 1, vv = val[x];
    for (int j = 0; j < v[x].size(); j++) {
      if (in[v[x][j]] == 0) continue;
      int k = fnd(v[x][j]);
      ans += o * (vv * sm * sz[k]);
      rep[k] = x;
      sz[x] += sz[k];
      sm += sz[k];
    }
    in[x] = 1;
  }
}
int main() {
  cin.tie(0);
  cout.tie(0);
  ios::sync_with_stdio(0);
  ios_base::sync_with_stdio(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    ord[i] = i;
    cin >> val[i];
  }
  for (int x, y, j = 0; j < n - 1; j++) {
    cin >> x >> y;
    x--;
    y--;
    v[x].push_back(y);
    v[y].push_back(x);
  }
  sort(ord, ord + n, cmp);
  bld();
  solve();
  reverse(ord, ord + n);
  o *= -1;
  bld();
  solve();
  cout << ans;
}
