class BinaryIndexedTree: def __init__(self,n,default = 10**9): self.s = [default]*(n+1) self.n = n # idxは0-indexted def reset(self,val,idx): idx += 1 while idx < self.n+1: self.s[idx] = min(self.s[idx], val) idx += idx&(-idx) return def get(self,idx): idx += 1 res = 10**9 while idx > 0: res = min(res, self.s[idx]) idx -= idx&(-idx) return res n = int(input()) A = list(map(int, input().split())) mod = 10**9 + 7 Rm = [[0]*n,[0]*n] B = sorted(range(n),key = lambda x:A[x]) ans = 10**9 for b in B: left = Rm[0][b] right = Rm[1][b] if left*right > 0: ans = min(ans, left + right + A[b]) idx = b while idx < n: if Rm[0][idx] != 0:break Rm[0][idx] = A[b] idx += 1 idx = b while idx >= 0: if Rm[1][idx] != 0:break Rm[1][idx] = A[b] idx -= 1 RM = [BinaryIndexedTree(n), BinaryIndexedTree(n)] for b in B[::-1]: left = RM[0].get(b) right = RM[1].get(n-b-1) if (10**9-left)*(10**9-right) > 0: ans = min(ans, left + right + A[b]) RM[0].reset(A[b], b) RM[1].reset(A[b], n-b-1) print(ans if ans != 10**9 else -1)