""" C++ の std::map ぽいデータ構造 座標圧縮は前提 n: 取りうる最大値(最小値は 0) self.dic を dict に取り換えることでメモリ節約できる """ class BIT: #0-indexed def __init__(self, n): self.size = n self.tree = [0]*(n+1) self.depth = n.bit_length() self.n0 = 1< 0: s += self.tree[i] i -= i & -i return s def query(self,l,r): #a_l + ... + a_r 閉区間 return self.get_sum(r) - self.get_sum(l-1) def add(self, i, x): i += 1 while i <= self.size: self.tree[i] += x i += i & -i # self.element[i] += x #def get(self,i): return element[i] def bisect_left(self,w): #和が w 以上になる最小の index #w が存在しない場合 self.size を返す if w <= 0: return 0 x,k = 0,self.n0 for _ in range(self.depth): k >>= 1 if x+k <= self.size and self.tree[x+k] < w: w -= self.tree[x+k] x += k return x class stdmap: def __init__(self, n): self.size = n+1 self.keys = set() self.B = BIT(n+1) #存在すれば 1、しないなら 0 self.dic = [0]*(n+1) # 値域 def __contains__(self, k): return k in self.keys def insert(self,a,b): # 値 a に b を上書き if a not in self.keys: self.B.add(a,1) self.keys.add(a) self.dic[a] = b def remove(self,a): # a を取り除く self.keys.remove(a) self.B.add(a,-1) def lower_bound(self,k): # k 以上の最小のkeyを求める return self.B.bisect_left(self.B.get_sum(k-1)+1) def kth_key(self,k): # k 番目に小さい元のkeyを求める return self.B.bisect_left(k) def kth_value(self,k): # k 番目に小さい元のmap先を求める return self.dic[self.B.bisect_left(k)] def prev_key(self,k): #一個前の元のkeyを求める idx = self.B.get_sum(k) assert idx != 0 return self.B.bisect_left(idx-1) def next_key(self,k): idx = self.B.get_sum(k) assert idx != self.size return self.B.bisect_left(idx+1) def __getitem__(self,item): return self.dic[item] # coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline n,*a = map(int,read().split()) sa = sorted(a+[0]+[1<<29]) zaatu = {ai:i for i,ai in enumerate(sa)} b1 = stdmap(n+2) b2 = stdmap(n+2) for i in range(n+2): b2.insert(i,1) b1.insert(0,1) b1.insert(n+1,1) ans = INF = 1<<30 n += 2 for i,ai in enumerate(a): z = zaatu[ai] b2.remove(z) i1 = b1.lower_bound(z) i2 = b2.lower_bound(z) if i1 < n and i2 < n: r = sa[i1] + ai + sa[i2] #print(r,z,i1,i2,ai) ans = min(ans,r) i1 = b1.kth_key(2) i2 = b2.kth_key(2) if i1 < z and i2 < z: r = sa[i1] + ai + sa[i2] #print(b2.keys) #print(r,z,i1,i2,ai) ans = min(ans,r) b1.insert(z,1) if ans==INF: print(-1) else: print(ans)