#pragma region #define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace atcoder; using mint = modint1000000007; //using mint = modint998244353; //using mint = modint; using namespace std; typedef long long ll; using vi = vector; using vvi = vector; using vl = vector; using vvl = vector; using pint = pair; using pll = pair; using vpint = vector; using vvpint = vector; using vmint = vector; using vvmint = vector; //#define rep(i, s, e) for (int(i) = (s); (i) < (e); ++(i)) #define rep(i, e) for (int(i) = 0; (i) < (e); ++(i)) #define rrep(i, s) for (int(i) = (s) - 1; (i) >= 0; --(i)) #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() #pragma region GCD ll gcd(ll a, ll b) { if (b == 0)return a; return gcd(b, a % b); } #pragma endregion #pragma region LCM ll lcm(ll a, ll b) { return a / gcd(a, b) * b; } #pragma endregion #pragma region chmin template inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } #pragma endregion #pragma region chmax template inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } #pragma endregion #pragma region グリッド内チェック bool out(int x, int y, int h, int w) { if (x < 0 || h <= x || y < 0 || w <= y)return true; else return false; } #pragma endregion #pragma region Dijkstra vl dijkstra(vector>> v, int s) { ll INF = 1e18; int MAX = 1e6; vl res(MAX, INF); priority_queue, vector>, greater>> q; q.push({ 0,s }); while (!q.empty()) { int now; ll d; tie(d, now) = q.top(); q.pop(); if (!chmin(res[now], d))continue; for (auto p : v[now]) { int next; ll c; tie(next, c) = p; if (res[next] <= res[now] + c)continue; q.push({ res[now] + c,next }); } } return res; } #pragma endregion #pragma endregion int main() { int n; cin >> n; vi a(n); rep(i, n)cin >> a[i]; vi lsmall(n), rsmall(n); lsmall[0] = a[0]; rsmall[n - 1] = a[n - 1]; for (int i = 1; i < n; ++i)lsmall[i] = min(lsmall[i - 1], a[i]); rrep(i, n - 1)rsmall[i] = min(rsmall[i + 1], a[i]); int res = 1e9; for (int i = 1; i < n - 1; ++i) { if (a[i] > lsmall[i - 1] && a[i] > rsmall[i + 1]) { chmin(res, a[i] + lsmall[i - 1] + rsmall[i + 1]); } } set l, r; l.insert(a[0]); rep(i, n - 1)r.insert(a[i + 1]); for (int i = 1; i < n - 1; ++i) { r.erase(a[i]); auto lit = l.lower_bound(a[i]); auto rit = r.lower_bound(a[i]); if (lit == l.end() || rit == r.end())continue; chmin(res, *lit + a[i] + *rit); } if (res == 1e9)cout << -1 << endl; else cout << res << endl; }