#include <bits/stdc++.h>
using namespace std;
void ga(int N, int *A) {
  for (int i(0); i < N; i++) scanf("%d", A + i);
}
int C[(1000006)], R[(1000006)];
int gc(int a) { return C[a] = (a == C[a] ? a : gc(C[a])); }
bool con(int a, int b) {
  if (gc(a) == gc(b)) return 0;
  R[C[a]] += R[gc(b)], C[C[b]] = C[a];
  return 1;
}
vector<int> g[(1000006)];
long long S;
int l, N, a, b, V[(1000006)], H[(1000006)], W[(1000006)];
bool cp(int a, int b) { return V[a] < V[b]; }
int main(void) {
  scanf("%d", &N), ga(N, V);
  for (int i(0); i < N - 1; i++)
    scanf("%d%d", &a, &b), g[--a].push_back(--b), g[b].push_back(a);
  iota(H, H + N, 0), sort(H, H + N, cp), (iota(C, C + N, 0), fill(R, R + N, 1));
  for (int i(0); i < N; i++) {
    long long T = 1;
    W[a = H[i]] = 1, S += V[a];
    for (auto &h : g[a])
      if (W[h]) S += R[gc(h)] * T * V[a], T += R[gc(h)], con(h, a);
  }
  reverse(H, H + N), (iota(C, C + N, 0), fill(R, R + N, 1)),
      (memset(W, 0, sizeof(W)));
  for (int i(0); i < N; i++) {
    long long T = 1;
    W[a = H[i]] = 1, S -= V[a];
    for (auto &h : g[a])
      if (W[h]) S -= R[gc(h)] * T * V[a], T += R[gc(h)], con(h, a);
  }
  printf("%lld\n", S);
  return 0;
}
