#include #include #include #include #include #include #include using namespace std; typedef long long ll; int N; int A[200000]; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; cin >> N; for(int i = 0; i < N; i++) { cin >> A[i]; A[i] *= -1; } int ans = -1e9; multiset stl, str; stl.insert(A[0]); for(int i = 2; i < N; i++) str.insert(A[i]); for(int i = 1; i < N-1; i++){ // < > auto l = lower_bound(stl.begin(), stl.end(), A[i]); auto r = lower_bound(str.begin(), str.end(), A[i]); if(l != stl.begin() && r != str.begin()){ l--; r--; if(*l != *r){ ans = max(ans, *l+*r+A[i]); }else{ if(l != stl.begin()){ l--; ans = max(ans, *l+*r+A[i]); l++; } if(r != stl.begin()){ r--; ans = max(ans, *l+*r+A[i]); r++; } } } // > < l = stl.end(); l--; r = str.end(); r--; if(*l > A[i] && *r > A[i]){ if(*l != *r){ ans = max(ans, *l+*r+A[i]); }else{ if(l != stl.begin()){ l--; if(*l > A[i]) ans = max(ans, *l+*r+A[i]); l++; } if(r != stl.begin()){ r--; if(*r > A[i]) ans = max(ans, *l+*r+A[i]); r++; } } } stl.insert(A[i]); str.erase(str.find(A[i+1])); } if(ans == -1e9){ cout << -1 << endl; }else{ cout << -ans << endl; } }