#include <bits/stdc++.h>
#pragma warning(disable : 4996)
#pragma comment(linker, "/STACK:336777216")
using namespace std;
int IT_MAX = 1 << 20;
long long MOD = 998244353;
const int INF = 0x3f3f3f3f;
const long long LL_INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1);
const double ERR = 1e-10;
int r[1000050];
int sz[1000050];
int root(int x) { return (x == r[x]) ? x : (r[x] = root(r[x])); }
int in[1000050];
bool chk[1000050];
vector<int> conn[1000050];
int u[1000050];
int main() {
  int N, i;
  scanf("%d", &N);
  for (i = 1; i <= N; i++) scanf("%d", &in[i]);
  for (i = 1; i < N; i++) {
    int t1, t2;
    scanf("%d %d", &t1, &t2);
    conn[t1].push_back(t2);
    conn[t2].push_back(t1);
  }
  for (i = 1; i <= N; i++) u[i] = i;
  sort(u + 1, u + N + 1, [](int a, int b) { return in[a] < in[b]; });
  long long ans = 0;
  memset(chk, 0, sizeof(chk));
  for (i = 1; i <= N; i++) r[i] = i, sz[i] = 1;
  for (i = 1; i <= N; i++) {
    int t = u[i];
    chk[t] = true;
    for (auto it : conn[t]) {
      if (!chk[it]) continue;
      int r1 = root(t), r2 = root(it);
      if (r1 == r2) continue;
      ans += (long long)sz[r1] * sz[r2] * in[t];
      sz[r2] += sz[r1];
      r[r1] = r2;
    }
  }
  memset(chk, 0, sizeof(chk));
  for (i = 1; i <= N; i++) r[i] = i, sz[i] = 1;
  for (i = N; i >= 1; i--) {
    int t = u[i];
    chk[t] = true;
    for (auto it : conn[t]) {
      if (!chk[it]) continue;
      int r1 = root(t), r2 = root(it);
      if (r1 == r2) continue;
      ans -= (long long)sz[r1] * sz[r2] * in[t];
      sz[r2] += sz[r1];
      r[r1] = r2;
    }
  }
  return !printf("%lld\n", ans);
}
