#include #include using namespace std; int main(){ int n;cin>>n; vector A(n),lmn(n+1),rmn(n+1),lmx(n+1),rmx(n+1); lmn[0] = rmn[0] = 1000000001; for(int i = 0; n > i; i++){ cin>>A[i]; } for(int i = 0; n > i; i++){ lmn[i+1] = min(lmn[i],A[i]); lmx[i+1] = max(lmx[i],A[i]); rmn[i+1] = min(rmn[i],A[n-i-1]); rmx[i+1] = max(rmx[i],A[n-i-1]); } long long ans = -1; for(int i = 1; n-1 > i; i++){ if(lmn[i] < A[i] && rmn[n-i-1] < A[i]){ if(ans == -1)ans = A[i]+lmn[i]+rmn[n-i-1]; else ans = min(ans,A[i]+lmn[i]+rmn[n-i-1]); } if(lmn[i] > A[i] && rmn[n-i-1] > A[i]){ if(ans == -1)ans = A[i]+lmx[i]+rmx[n-i-1]; else ans = min(ans,A[i]+lmx[i]+rmx[n-i-1]); } } cout << ans << endl; }