#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <ctime>
#include <map>
#include <queue>
#include <cstdlib>
#include <string>
#include <climits>
#include <set>
#include <vector>
#define int long long
using namespace std;
inline int read(){
int k=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){k=k*10+ch-'0';ch=getchar();}
return k*f;
}
inline void write(int x){
if(x<0)putchar('-'),x=-x;
if(x>9)write(x/10);putchar(x%10+'0');
}
inline void writeln(int x){
write(x);puts("");
}
struct ppap{int x,y;}a[100010];
inline bool cmp(ppap a,ppap b){return a.y<b.y;}
inline bool cmpp(ppap a,ppap b){return a.y>b.y;}
int n,nedge=0,p[200010],nex[200010],head[200010];
int fa[100010],s[100010];
inline void addedge(int a,int b){
p[++nedge]=b;nex[nedge]=head[a];head[a]=nedge;
}
inline int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}
inline int work(){
for(int i=1;i<=n;i++)fa[i]=i,s[i]=1;
int ans=0;
for(int i=1;i<=n;i++){
int fx=find(a[i].x);int q=s[fx];
for(int k=head[a[i].x];k;k=nex[k])if(find(p[k])!=fx){
int fy=find(p[k]);
q*=s[fy];fa[fy]=fx;s[fx]+=s[fy];
}
ans=ans+q*a[i].y;
}
return ans;
}
signed main()
{
n=read();
for(int i=1;i<=n;i++)a[i].x=i,a[i].y=read();
sort(a+1,a+n+1,cmp);
for(int i=1;i<n;i++){
int x=read(),y=read();
addedge(x,y);addedge(y,x);
}
int ans1=work();
sort(a+1,a+n+1,cmpp);
int ans2=work();
writeln(ans1-ans2);
}