class SegmentTree: def __init__(self, size, f=min, default=10 ** 18): self.size = 2**(size-1).bit_length() self.default = default self.dat = [default]*(self.size*2) self.f = f def update(self, i, x): i += self.size self.dat[i] = x while i > 0: i >>= 1 self.dat[i] = self.f(self.dat[i*2], self.dat[i*2+1]) def query(self, l, r): l += self.size r += self.size lres, rres = self.default, self.default while l < r: if l & 1: lres = self.f(lres, self.dat[l]) l += 1 if r & 1: r -= 1 rres = self.f(self.dat[r], rres) l >>= 1 r >>= 1 res = self.f(lres, rres) return res N = int(input()) A = list(map(int, input().split())) B = [0] * N for i in range(N): B[i] = (A[i], i + 1) B.sort(reverse=True) inf = 10 ** 18 T = SegmentTree(N + 2) ans = inf for a, i in B: x = T.query(0, i) y = T.query(i + 1, N + 2) ans = min(ans, x + a + y) T.update(i, a) for i, a in enumerate(A): i += 1 x = T.query(0, i) y = T.query(i + 1, N + 2) if x > a or y > a: continue ans = min(ans, x + a + y) print(ans) if ans < inf else print(-1)