#include using namespace std; #define rep(i, n) for(int i=0, i##_len=(n); i=0; --i) #define rreps(i, n) for(int i=((int)(n)); i>0; --i) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define sz(x) ((int)(x).size()) #define pl(s) cout << (s) << "\n"; #define pls(...) {bool space = false; for(auto i : __VA_ARGS__) (cout << (space?" ":"") << i), space = true; cout << "\n";} #define plexit(s) {cout << (s) << "\n"; exit(0);} #define yes(s) cout << ((s)?"Yes":"No") << "\n"; #define pb push_back #define pcnt __builtin_popcountll template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } #ifdef __LOCAL #include #define dump(...) \ DUMPOUT << " " << string(#__VA_ARGS__) << ": " \ << "[" << to_string(__LINE__) << ":" << __FUNCTION__ << "]" \ << endl \ << " ", \ dump_func(__VA_ARGS__) #else #define dump(...) #endif struct IOInit { static constexpr int IOS_PREC = 15; static constexpr bool AUTOFLUSH = false; IOInit() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(IOS_PREC); dump(IOS_PREC); if(AUTOFLUSH) cout << unitbuf; } } IO_INIT; using i64 = std::int_fast64_t; using i128 = __int128_t; using ll = long long; using ull = unsigned long long; using ld = long double; using pii = std::pair; using pll = std::pair; using vi = std::vector; using vvi = std::vector>; using vl = std::vector; using vp = std::vector; signed main(void) { int N; cin >> N; vi A(N); rep(i,N) cin >> A[i]; int ans = 1e9+7; vi ls(N), rs(N); ls.front() = A.front(); rs.back() = A.back(); reps(i,N-1) ls[i] = min(ls[i-1],A[i]); rrep(i,N-1) rs[i] = min(rs[i+1],A[i]); //dump(ls,rs); reps(i,N-2) { int a = ls[i-1]; int b = A[i]; int c = rs[i+1]; if (max({a,b,c}) != b && min({a,b,c}) != b) continue; chmin(ans,a+b+c); //dump(ans,a,b,c); } if (ans == 1e9+7) plexit("-1") pl(ans) return 0; }