Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. [Image] 

There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength a_{i}.

Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.

When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.

To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met:  Bank x is online. That is, bank x is not hacked yet.  Bank x is neighboring to some offline bank.  The strength of bank x is less than or equal to the strength of Inzane's computer. 

Determine the minimum strength of the computer Inzane needs to hack all the banks.


-----Input-----

The first line contains one integer n (1 ≤ n ≤ 3·10^5) — the total number of banks.

The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the strengths of the banks.

Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — meaning that there is a wire directly connecting banks u_{i} and v_{i}.

It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.


-----Output-----

Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.


-----Examples-----
Input
5
1 2 3 4 5
1 2
2 3
3 4
4 5

Output
5
Input
7
38 -29 87 93 39 28 -55
1 2
2 5
3 2
2 4
1 7
7 6

Output
93
Input
5
1 2 7 6 7
1 5
5 3
3 4
2 4

Output
8


-----Note-----

In the first sample, Inzane can hack all banks using a computer with strength 5. Here is how:  Initially, strengths of the banks are [1, 2, 3, 4, 5].  He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ].  He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ].  He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ].  He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ].  He completes his goal by hacking bank 1. 

In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.

Difficulty: HARD
Tags: Tree algorithms

Dynamic programming

Data structures

Constructive algorithms
Skill types: Dynamic programming

Data structures

Starter code:

Solutions:
import sys

def solve():
	n = int(sys.stdin.readline())
	d = list(map(int, sys.stdin.readline().split()))
	s = [[] for g in d]
	mx_tmp = max(d)
	mx_tmp2 = max((g for g in d + [-2000000000.0] if g < mx_tmp))
	mxpt = [mx_tmp, mx_tmp2]
	mxcnt = [d.count(mx_tmp), d.count(mx_tmp2)]
	for i in range(1, n):
		(a, b) = map(int, sys.stdin.readline().split())
		a -= 1
		b -= 1
		s[a] += [b]
		s[b] += [a]
	mx = int(2000000000.0)
	for i in range(n):
		nmx = [] + mxcnt
		tmpmax = d[i]
		for k in s[i]:
			if d[k] == mxpt[0]:
				nmx[0] -= 1
			elif d[k] == mxpt[1]:
				nmx[1] -= 1
		if nmx[0] != mxcnt[0]:
			tmpmax = mxpt[0] + 1
		elif nmx[1] != mxcnt[1]:
			tmpmax = max(tmpmax, mxpt[1] + 1)
		if d[i] == mxpt[0]:
			nmx[0] -= 1
		elif d[i] == mxpt[1]:
			nmx[1] -= 1
		if nmx[0]:
			tmpmax = mxpt[0] + 2
		elif nmx[1]:
			tmpmax = max(mxpt[1] + 2, tmpmax)
		mx = min(mx, tmpmax)
	print(mx)

def __starting_point():
	solve()
__starting_point()


import sys

def solve():
	n = int(sys.stdin.readline().rstrip())
	a = [int(i) for i in sys.stdin.readline().split()]
	Adj = [[] for i in range(n)]
	for i in range(n - 1):
		(u, v) = map(int, sys.stdin.readline().split())
		(u, v) = (u - 1, v - 1)
		Adj[u].append(v)
		Adj[v].append(u)
	max_v = max(a)
	max_n = a.index(max_v)
	num_m = sum((ai == max_v for ai in a))
	if num_m == 1:
		ans = max_v
		rinsetu = [False] * n
		for u in Adj[max_n]:
			rinsetu[u] = True
		rinsetu[max_n] = True
		for u in range(n):
			if rinsetu[u]:
				continue
			if a[u] == max_v - 1:
				ans = max_v + 1
				break
	else:
		for u in range(n):
			cnt = 0
			if a[u] == max_v:
				cnt += 1
			for v in Adj[u]:
				if a[v] == max_v:
					cnt += 1
			if cnt == num_m:
				ans = max_v + 1
				break
		else:
			ans = max_v + 2
	print(ans)

def debug(x, table):
	for (name, val) in table.items():
		if x is val:
			print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
			return None

def __starting_point():
	solve()
__starting_point()


def main():
	n = int(input())
	a = list(map(int, input().split()))
	graph = [[] for _ in range(n)]
	for i in range(n - 1):
		(u, v) = map(lambda x: int(x) - 1, input().split())
		graph[u].append(v)
		graph[v].append(u)
	a_max = max(a)
	max_count_0 = sum((ai == a_max for ai in a))
	prev_count_0 = sum((ai == a_max - 1 for ai in a))
	result = a_max + 2
	for u in range(n):
		max_count = max_count_0
		prev_count = prev_count_0
		if a[u] == a_max:
			max_count -= 1
		else:
			prev_count -= 1
		for v in graph[u]:
			if a[v] == a_max:
				max_count -= 1
				prev_count += 1
			elif a[v] == a_max - 1:
				prev_count -= 1
		if max_count == 0:
			if prev_count == 0:
				result = a_max
				break
			else:
				result = a_max + 1
	print(result)
main()


from collections import defaultdict
from math import log2
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.setrecursionlimit(10 ** 5)

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
n = int(input())
b = [0] + list(map(int, input().split()))
m = max(b[1:])
ans = m + 2
d = defaultdict(lambda : 0)
adj = [[] for i in range(n + 1)]
l = []
for j in range(1, n + 1):
	b[j] += 2
	d[b[j]] += 1
for i in range(n - 1):
	(u, v) = map(int, input().split())
	adj[u].append(v)
	adj[v].append(u)
for i in range(1, n + 1):
	d[b[i]] += -1
	d[b[i] - 2] += 1
	for j in adj[i]:
		d[b[j]] += -1
		d[b[j] - 1] += 1
	if d[m + 2] == 0:
		if d[m + 1] == 0:
			ans = min(ans, m)
		else:
			ans = min(ans, m + 1)
	d[b[i]] += 1
	d[b[i] - 2] += -1
	for j in adj[i]:
		d[b[j]] += 1
		d[b[j] - 1] += -1
print(ans)


n = int(input())
strengths = list(map(int, input().split()))
max_strength = max(strengths)
count_max = strengths.count(max_strength)
count_second_place = strengths.count(max_strength - 1)
maxes = [0 for i in range(n)]
second_places = [0 for i in range(n)]
for i in range(n - 1):
	(a, b) = list(map(int, input().split()))
	a -= 1
	b -= 1
	if strengths[a] == max_strength:
		maxes[b] += 1
	elif strengths[a] == max_strength - 1:
		second_places[b] += 1
	if strengths[b] == max_strength:
		maxes[a] += 1
	elif strengths[b] == max_strength - 1:
		second_places[a] += 1
total_max = 1000000009
for i in range(n):
	here = 0
	if strengths[i] < max_strength:
		if maxes[i] == count_max:
			here = max_strength + 1
		else:
			here = max_strength + 2
	elif count_max == 1:
		if second_places[i] == count_second_place:
			here = max_strength
		else:
			here = max_strength + 1
	elif maxes[i] == count_max - 1:
		here = max_strength + 1
	else:
		here = max_strength + 2
	total_max = min(total_max, here)
print(total_max)


from collections import defaultdict, Counter
n = int(input())
a = list((int(v) for v in input().split())) + [-1000000002]
c = Counter(a)
(top, sec) = sorted(set(a))[-1:-3:-1]
(topC, secC) = ([0] * n, [0] * n)
for i in range(n - 1):
	(u, v) = (int(v) for v in input().split())
	if a[u - 1] == top:
		topC[v - 1] += 1
	if a[v - 1] == top:
		topC[u - 1] += 1
	if a[u - 1] == sec:
		secC[v - 1] += 1
	if a[v - 1] == sec:
		secC[u - 1] += 1
ans = top + 2
for i in range(n):
	add = 1 if a[i] == top else 0
	if topC[i] + add < c[top]:
		continue
	best = top + 1 if topC[i] else top
	add = 1 if a[i] == sec else 0
	if secC[i] + add < c[sec]:
		best = max(best, sec + 2)
	ans = min(ans, best)
print(ans)


import sys
n = int(sys.stdin.readline())
d = list(map(int, sys.stdin.readline().split()))
s = [[] for g in d]
mxpt = [-2000000000.0, -2000000000.0]
mxcnt = [0, 0]
for i in d:
	if i > mxpt[0]:
		mxpt[1] = mxpt[0]
		mxcnt[1] = mxcnt[0]
		mxpt[0] = i
		mxcnt[0] = 1
	elif i == mxpt[0]:
		mxcnt[0] += 1
	elif i > mxpt[1]:
		mxpt[1] = i
		mxcnt[1] = 1
	else:
		mxcnt[1] += i == mxpt[1]
for i in range(1, n):
	(a, b) = map(int, sys.stdin.readline().split())
	a -= 1
	b -= 1
	s[a] += [b]
	s[b] += [a]
mx = int(2000000000.0)
for i in range(n):
	nmx = [] + mxcnt
	tmpmax = d[i]
	for k in s[i]:
		if d[k] == mxpt[0]:
			nmx[0] -= 1
		elif d[k] == mxpt[1]:
			nmx[1] -= 1
	if nmx[0] != mxcnt[0]:
		tmpmax = mxpt[0] + 1
	elif nmx[1] != mxcnt[1]:
		tmpmax = max(tmpmax, mxpt[1] + 1)
	if d[i] == mxpt[0]:
		nmx[0] -= 1
	elif d[i] == mxpt[1]:
		nmx[1] -= 1
	if nmx[0]:
		tmpmax = mxpt[0] + 2
	elif nmx[1]:
		tmpmax = max(mxpt[1] + 2, tmpmax)
	mx = min(mx, tmpmax)
print(mx)


import random
n = int(input())
strengths = list(map(int, input().split()))
l = [[] for i in range(n)]
for j in range(n - 1):
	(a, b) = map(int, input().split())
	l[a - 1].append(b - 1)
	l[b - 1].append(a - 1)
hacked = max(strengths)
greatest_value = sum((i == hacked for i in strengths))
result = hacked
if greatest_value == 1:
	computer = strengths.index(result)
	adjlist = set(l[computer])
	adjlist.add(computer)
	for i in range(n):
		if i in adjlist:
			continue
		if strengths[i] == hacked - 1:
			result += 1
			break
else:
	for i in range(n):
		count = 0
		if strengths[i] == hacked:
			count += 1
		for v in l[i]:
			if strengths[v] == hacked:
				count += 1
		if count == greatest_value:
			result += 1
			break
	else:
		result += 2
print(result)


import sys
input = sys.stdin.readline
from collections import Counter
n = int(input())
arr = list((int(i) for i in input().split())) + [-int(1000000000.0 + 3)]
c = Counter(arr)
(top, sec) = sorted(set(arr))[-1:-3:-1]
top_cnt = [int(i == top) for i in arr]
sec_cnt = [int(i == sec) for i in arr]
edges = list((list(map(int, input().split())) for _ in range(n - 1)))
for (u, v) in edges:
	if arr[u - 1] == top:
		top_cnt[v - 1] += 1
	if arr[v - 1] == top:
		top_cnt[u - 1] += 1
	if arr[u - 1] == sec:
		sec_cnt[v - 1] += 1
	if arr[v - 1] == sec:
		sec_cnt[u - 1] += 1
res = top + 2
for i in range(n):
	if top_cnt[i] < c[top]:
		continue
	if top_cnt[i] == 1 and arr[i] == top:
		curr = top
	else:
		curr = top + 1
	if sec_cnt[i] < c[sec]:
		curr = max(curr, sec + 2)
	res = min(res, curr)
print(res)


def sol():
	n = int(input())
	st = list(map(int, input().split(' ')))
	d = {}
	for x in range(n):
		d[x] = []
	st = [(st[i], i) for i in range(len(st))]
	st = sorted(st)
	for a0 in range(n - 1):
		(u, v) = map(int, input().split(' '))
		(u, v) = (u - 1, v - 1)
		d[u].append(v)
		d[v].append(u)
	hardest = []
	almost = []
	single_hardest = st[-1][0]
	for x in st[::-1]:
		if x[0] == single_hardest:
			hardest.append(x[1])
		elif x[0] == single_hardest - 1:
			almost.append(x[1])
		else:
			break

	def inter(a, b):
		c = []
		for x in a:
			if x in b:
				c.append(x)
		return c
	lower_bound = single_hardest
	inte = d[hardest[0]] + [hardest[0]]
	for h in hardest[1:]:
		inte = inter(inte, d[h] + [h])
	if not inte:
		return single_hardest + 2
	if len(hardest) > 1:
		return single_hardest + 1
	if not almost:
		return single_hardest
	cand = st[-1][1]
	for h in almost:
		if h not in d[cand]:
			return single_hardest + 1
	return single_hardest
print(sol())