#pragma region #pragma GCC target("avx2") #pragma GCC optimize("03") #pragma GCC optimize("unroll-loops") #include using namespace std; typedef long double ld; typedef long long ll; typedef unsigned long long ull; #define endl "\n" #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define PII pair #define PLL pair #define VPII vector #define VPLL vector #define ALL(x) (x).begin(), (x).end() constexpr int INF=1<<30; constexpr ll LINF=1LL<<60; constexpr ll mod=1e9+7; constexpr int NIL = -1; templateinline bool chmax(T &a, const T &b) { if (ainline bool chmin(T &a, const T &b) { if (b mn(MX); vector rmn(MX); ll cur = LINF; FOR(i,0,n-1) { chmin(cur, a[i]); mn[i] = cur; } cur = LINF; FOR(i,0,n-1) { chmin(cur, a[n-1-i]); rmn[n-1-i] = cur; } ll ans = LINF; FOR(i,1,n-2) { if(mn[i-1] < a[i] and a[i] > rmn[i+1]) { chmin(ans, a[i] + mn[i-1] + rmn[i+1]); } } set st; st.insert(a[0]); FOR(i,1,n-1) { mn[i] = *upper_bound(ALL(st), a[i]); st.insert(a[i]); } st.clear(); st.insert(a[n-1]); for(int i=n-2; i>=0; i--) { rmn[i] = *upper_bound(ALL(st), a[i]); st.insert(a[i]); } FOR(i,1,n-2) { if(mn[i] > a[i] and a[i] < rmn[i]) { chmin(ans, mn[i] + a[i] + rmn[i]); } } return ans; } int main(){ cin.tie(0); ios::sync_with_stdio(false); //cout << fixed << setprecision(15); cin >> n; FOR(i,0,n-1) cin >> a[i]; ll ans = solve(); if(ans == LINF) { cout << -1 << endl; return 0; } else { cout << ans << endl; return 0; } return 0; }