#include #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(ri,n) for(int ri = (int)(n-1); ri >= 0; ri--) #define rep2(i,x,n) for(int i = (int)(x); i < (int)(n); i++) #define rrep2(ri,x,n) for(int ri = (int)(n-1); ri >= (int)(x); ri--) #define repit(itr,x) for(auto itr = x.begin(); itr != x.end(); itr++) #define rrepit(ritr,x) for(auto ritr = x.rbegin(); ritr != x.rend(); ritr++) #define ALL(x) x.begin(), x.end() using ll = long long; using namespace std; const int INF = 1001001001; int main(){ int n; cin >> n; vector a(n); int mn = INF, mni; rep(i, n){ cin >> a.at(i); if(mn > a.at(i)){ mn = a.at(i); mni = i; } } int ans = INF; if(mni != 0 && mni != n-1){ int lmn = INF, rmn = INF; rep(i, mni){ lmn = min(lmn, a.at(i)); } rep2(i, mni+1, n){ rmn = min(rmn, a.at(i)); } ans = lmn + rmn + mn; } vector smn(n, INF); smn.back() = a.back(); smn.front() = a.front(); rrep2(i, mni, n-1){ smn.at(i) = min(a.at(i), smn.at(i+1)); } rep2(i, 1, mni){ smn.at(i) = min(a.at(i), smn.at(i-1)); } rrep2(i, mni+1, n-1){ if(a.at(i) < smn.at(i+1)) continue; int add = mn + a.at(i) + smn.at(i+1); ans = min(ans, add); } rrep2(i, 1, mni){ if(a.at(i) < smn.at(i-1)) continue; int add = mn + a.at(i) + smn.at(i-1); ans = min(ans, add); } if(ans == INF) ans = -1; cout << ans << endl; return 0; }