import sys sys.setrecursionlimit(200005) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.buffer.readline()) def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def LI1(): return list(map(int1, sys.stdin.buffer.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def LLI1(rows_number): return [LI1() for _ in range(rows_number)] def BI(): return sys.stdin.buffer.readline().rstrip() def SI(): return sys.stdin.buffer.readline().rstrip().decode() dij = [(0, 1), (-1, 0), (0, -1), (1, 0)] # dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] inf = 10**16 # md = 998244353 # md = 10**9+7 class BIT: def __init__(self, n): self.inf = 10**16 self.n = n+3 self.table = [self.inf]*(self.n+1) def update(self, i, x): i += 1 while i <= self.n: if x < self.table[i]: self.table[i] = x i += i & -i def min(self, i): i += 1 res = self.inf while i > 0: if self.table[i] < res: res = self.table[i] i -= i & -i return res n = II() aa = LI() def make_mn(aa): res = [] mn = inf for a in aa: if mn < a: res.append(mn) else: res.append(inf) mn = min(mn, a) return res ll = make_mn(aa) rr = make_mn(aa[::-1])[::-1] ans = inf for a, l, r in zip(aa, ll, rr): ans = min(ans, a+l+r) def make_mx(aa): bit = BIT(n) res = [inf]*n for i, a in sorted(enumerate(aa), key=lambda x: -x[1]): mn = bit.min(i-1) res[i] = mn bit.update(i, a) return res ll = make_mx(aa) rr = make_mx(aa[::-1])[::-1] for a, l, r in zip(aa, ll, rr): ans = min(ans, a+l+r) if ans == inf: ans = -1 print(ans)