#include using namespace std; 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; } void debug() { cerr << "\n"; } template void debug(const T &x) { cerr << x << "\n"; } template void debug(const T &x, const Args &... args) { cerr << x << " "; debug(args...); } template void debugVector(const vector &v) { for(const T &x : v) { cerr << x << " "; } cerr << "\n"; } using ll = long long; #define ALL(v) (v).begin(), (v).end() #define RALL(v) (v).rbegin(), (v).rend() const double EPS = 1e-7; const int INF = 1 << 30; const ll LLINF = 1LL << 60; const double PI = acos(-1); constexpr int MOD = 1000000007; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; //------------------------------------- template struct SegmentTree { using F = function; private: int n; vector node; Monoid E; F f; public: SegmentTree(vector v, Monoid e, const F func) : f(func), E(e) { int sz = v.size(); n = 1; while(n < sz) { n *= 2; } node.resize(2 * n - 1, E); for(int i = 0; i < sz; i++) { node[i + n - 1] = v[i]; } for(int i = n - 2; i >= 0; i--) { node[i] = f(node[2 * i + 1], node[2 * i + 2]); } } void update(int i, Monoid val) { i += (n - 1); node[i] = val; while(i > 0) { i = (i - 1) / 2; node[i] = f(node[2 * i + 1], node[2 * i + 2]); } } Monoid query(int a, int b, int i = 0, int l = 0, int r = -1) { if(r < 0) { r = n; } if(r <= a || b <= l) { return E; } if(a <= l && r <= b) { return node[i]; } Monoid vl = query(a, b, 2 * i + 1, l, (l + r) / 2); Monoid vr = query(a, b, 2 * i + 2, (l + r) / 2, r); return f(vl, vr); } Monoid operator[](const int &i) const { return node[i + n - 1]; } }; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector a(n); for(auto &it : a) { cin >> it; } SegmentTree segmin(a, LLINF, [](ll x, ll y) { return min(x, y); }); ll ans = LLINF; // min max minを探す for(int i = 0; i < n; i++) { ll l = segmin.query(0, i); ll r = segmin.query(i + 1, n); if(l < a[i] && r < a[i]) { chmin(ans, l + a[i] + r); } } // 大小大 vector memo = a; // 今見てる要素より左にあって、今見てる要素よりも大きいa[i]の集合 set se; for(int i = 0; i < n; i++) { while(!se.empty()) { if(*se.begin() >= a[i]) { break; } else { se.erase(se.begin()); } } if(se.empty()) { memo[i] += LLINF; } else { memo[i] += *se.begin(); } se.insert(a[i]); } se.clear(); for(int i = n - 1; i >= 0; i--) { while(!se.empty()) { if(*se.begin() > a[i]) { break; } else { se.erase(se.begin()); } } if(se.empty()) { memo[i] += LLINF; } else { memo[i] += *se.begin(); } se.insert(a[i]); } chmin(ans, *min_element(ALL(memo))); cout << (ans >= LLINF ? -1 : ans) << endl; }