#include <bits/stdc++.h>
using namespace std;
int n, par[1000005], si[1000005], ta, tb;
pair<int, int> p[1000005];
vector<int> ne[1000005];
bool u[1000005];
long long ans, tc;
int find(int a) { return par[a] == a ? a : par[a] = find(par[a]); }
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &p[i].first);
    p[i].second = i + 1;
  }
  sort(p, p + n);
  for (int i = 1; i < n; i++) {
    scanf("%d%d", &ta, &tb);
    ne[ta].push_back(tb);
    ne[tb].push_back(ta);
  }
  for (int i = 0; i < n; i++) {
    u[ta = p[i].second] = 1;
    par[ta] = ta;
    si[ta] = 1;
    tc = 0;
    for (int j = 0; j < ne[ta].size(); j++)
      if (u[ne[ta][j]]) {
        tb = find(ne[ta][j]);
        tc += (long long)si[ta] * si[tb];
        si[ta] += si[tb];
        par[tb] = ta;
      }
    ans += (long long)p[i].first * tc;
  }
  for (int i = n - 1; i >= 0; i--) {
    u[ta = p[i].second] = 0;
    par[ta] = ta;
    si[ta] = 1;
    tc = 0;
    for (int j = 0; j < ne[ta].size(); j++)
      if (!u[ne[ta][j]]) {
        tb = find(ne[ta][j]);
        tc += (long long)si[ta] * si[tb];
        si[ta] += si[tb];
        par[tb] = ta;
      }
    ans -= (long long)p[i].first * tc;
  }
  printf("%lld\n", ans);
  return 0;
}
