#include <bits/stdc++.h>
class Solver {
  size_t n;
  std::vector<std::pair<int64_t, int>> a_ind;
  std::vector<int64_t> a_value;
  std::vector<std::vector<int>> tree;
  std::vector<int> parent;
  std::vector<int64_t> size;

 public:
  Solver() = default;
  void read() {
    std::cin >> n;
    a_ind.resize(n);
    a_value.resize(n);
    tree.resize(n);
    for (int i = 0; i < n; ++i) {
      int64_t a;
      std::cin >> a;
      a_ind[i].first = a;
      a_ind[i].second = i;
    }
    std::sort(
        a_ind.begin(), a_ind.end(),
        [](const std::pair<int64_t, int>& a, const std::pair<int64_t, int>& b) {
          return a.first < b.first;
        });
    std::vector<int> subst(n);
    for (int i = 0; i < n; ++i) {
      subst[a_ind[i].second] = i;
    }
    for (int i = 0; i < n - 1; ++i) {
      int a, b;
      std::cin >> a >> b;
      a = subst[a - 1];
      b = subst[b - 1];
      tree[a].push_back(b);
      tree[b].push_back(a);
    }
  }
  void solve() {
    parent.resize(n);
    size.resize(n);
    auto max = get_max();
    auto min = get_min();
    std::cout << max - min << std::endl;
  }
  void write() {}
  void init_dsu() {
    for (int i = 0; i < n; ++i) {
      parent[i] = i;
    }
    size.assign(n, 1L);
  }
  int find_set(int x) {
    if (parent[x] == x) {
      return x;
    }
    return parent[x] = find_set(parent[x]);
  }
  int64_t get_max() {
    init_dsu();
    int64_t sum_of_maxs = 0;
    for (int root = 0; root < n; ++root) {
      int64_t a = a_ind[root].first;
      int64_t sum_of_sizes = 1;
      int64_t sum_of_squares = 1;
      for (auto child : tree[root]) {
        if (child < root) {
          int64_t S = size[find_set(child)];
          sum_of_sizes += S;
          sum_of_squares += S * S;
          parent[find_set(child)] = root;
        }
      }
      size[root] = sum_of_sizes;
      int64_t count_of_paths =
          (sum_of_sizes * sum_of_sizes - sum_of_squares) / 2 + 1;
      sum_of_maxs += count_of_paths * a;
    }
    return sum_of_maxs;
  }
  int64_t get_min() {
    init_dsu();
    int64_t sum_of_maxs = 0;
    for (int root = n - 1; root >= 0; --root) {
      int64_t a = a_ind[root].first;
      int64_t sum_of_sizes = 1;
      int64_t sum_of_squares = 1;
      for (auto child : tree[root]) {
        if (child > root) {
          int64_t S = size[find_set(child)];
          sum_of_sizes += S;
          sum_of_squares += S * S;
          parent[find_set(child)] = root;
        }
      }
      size[root] = sum_of_sizes;
      int64_t count_of_paths =
          (sum_of_sizes * sum_of_sizes - sum_of_squares) / 2 + 1;
      sum_of_maxs += count_of_paths * a;
    }
    return sum_of_maxs;
  }
};
int main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr);
  Solver solver;
  solver.read();
  solver.solve();
  solver.write();
  return 0;
}
