#include #include //#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define INF 1e18 #define rep(i,n)for(int i=0;(i)<(int)(n);i++) #define REP(i,a,b)for(int i=(int)(a);(i)<=(int)(b);i++) #define VEC(type, c, n) std::vector c(n);for(auto& i:c)std::cin>>i; #define vec(type,n) vector(n) #define vvec(m,n) vector> (int(m),vector(n)) #define ALL(a) (a).begin(),(a).end() using namespace std; using ll = long long; using Graph = vector>; using P = pair; const ll MOD = INF + 7; int main(){ int n; cin >> n; ll res = INF; vector a(n), sa(n); bool f = true; int up = 0, down = 0; rep(i, n){ cin >> a[i]; if(i == 0)continue; if(a[i - 1] > a[i])down++; if(a[i - 1] < a[i])up++; } if(down == 0 || up == 0){ cout << -1 << endl; return 0; } vector max_l(n), max_r(n), min_l(n), min_r(n); rep(i, n){ if(i == 0){ //max_l[i] = a[i]; min_l[i] = a[i]; } else { //max_l[i] = max(max_l[i - 1], a[i]); min_l[i] = min(min_l[i - 1], a[i]); } } reverse(ALL(a)); rep(i, n){ if(i == 0){ //max_r[i] = a[i]; min_r[i] = a[i]; } else { //max_r[i] = max(max_r[i - 1], a[i]); min_r[i] = min(min_r[i - 1], a[i]); } } reverse(ALL(a)); REP(i, 1, n - 2){ ll am = INF, aM = INF; if(a[i] > min_l[i - 1] && a[i] > min_r[n - i - 2])am = a[i] + min_l[i - 1] + min_r[n - i - 2]; //if(a[i] < max_l[i - 1] && a[i] < max_r[n - i - 1])aM = a[i] + max_l[i - 1] + max_r[n - i - 1]; res = min({res, am, aM}); } cout << res << endl; }