#include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //input from stdin istream& operator >> (istream& is, vector& vec){for(int& val: vec) scanf("%d", &val); return is;} istream& operator >> (istream& is, vector& vec){for(long long& val: vec) scanf("%lld", &val); return is;} istream& operator >> (istream& is, vector& vec){for(double& val: vec) scanf("%lf", &val); return is;} char buff[200000]; istream& operator >> (istream& is, vector& vec){for(string& val: vec) {scanf("%s", buff); val=buff;}; return is;} template istream& operator >> (istream& is, vector& vec){for(T& val: vec) is >> val; return is;} template istream& operator , (istream& is, T& val){ return is >> val;} template ostream& operator << (ostream& os, const vector& vec){for(int i=0; i ostream& operator , (ostream& os, const T& val){ return os << " " << val;} template ostream& operator >> (ostream& os, const T& val){ return os << " " << val;} long long dfs(vector& a, vector>& G, int pos, int last, long long& ans){ map dp; for(int next : G[pos]){ if(next == last) continue; long long tmp = dfs(a,G, next, pos, ans); if(a[next] == a[pos]) continue; if(dp.find(a[next]) != dp.end()) dp[a[next]] = max(dp[a[next]], tmp); else dp[a[next]] = tmp; ans = max(ans, tmp); } long long l = 0; long long l_cnt = 0; long long s = 0; long long s_cnt = 0; for(auto v : dp){ if(v.first < a[pos]){ s += v.second; s_cnt++; }else if(v.first > a[pos]){ l += v.second; l_cnt++; } } ans = max({ans, l + l_cnt*(l_cnt-1)/2, s + s_cnt*(s_cnt-1)/2}); if(last == pos) return 0; if(a[pos] == a[last]) return 0; if(a[pos] < a[last]){ if(dp.find(a[last]) != dp.end()){ l -= dp[a[last]]; l_cnt--; } return l + l_cnt*(l_cnt-1)/2 + l_cnt; }else if(a[pos] > a[last]){ if(dp.find(a[last]) != dp.end()){ s -= dp[a[last]]; s_cnt--; } return s + s_cnt*(s_cnt-1)/2 + s_cnt; } return 0; } int main(){ int n; cin >> n; vector a(n); cin >> a; vector> G(n); for(int i=0; i> u,v; scanf("%d%d", &u,&v); u--; v--; G[u].push_back(v); G[v].push_back(u); } long long ans = 0; dfs(a,G, 0,0, ans); cout << ans << endl; return 0; }