#include #include #include #include #include #include #include #include #include #include #include #include typedef unsigned long long ULLONG; typedef long long LLONG; static const LLONG MOD_NUM = 1000000007;//998244353; template static void getval(_T& a) { std::cin >> a; } template static void getval(_T& a, _T& b) { std::cin >> a >> b; } template static void getval(_T& a, _T& b, _T& c) { std::cin >> a >> b >> c; } static void exec(); int main() { exec(); fflush(stdout); return 0; } static void exec() { int N; getval(N); int INF = MOD_NUM * 2LL; LLONG minVal = INF; int minIdx = -1; std::vector ai(N); for (int i = 0; i < N; i++) { getval(ai[i]); if (minVal > ai[i]) { minVal = ai[i]; minIdx = i; } } LLONG ans = 0; LLONG fMin = INF, fPeak = INF, fFst = INF; std::set fs; for (int i = minIdx - 1; i >= 0; i--) { if (fMin > ai[i]) { fMin = ai[i]; } if (fFst > ai[i]) { auto f = fs.lower_bound(ai[i]); if (f != fs.end()) { fFst = ai[i]; fPeak = *f; } } fs.insert(ai[i]); } fs.erase(fs.begin(), fs.end()); LLONG lMin = INF, lPeak = INF, lLast = INF; for (int i = minIdx + 1; i < N; i++) { if (lMin > ai[i]) { lMin = ai[i]; } if (lLast > ai[i]) { auto l = fs.lower_bound(ai[i]); if (l != fs.end()) { lLast = ai[i]; lPeak = *l; } } fs.insert(ai[i]); } ans = std::min({ fMin + minVal + lMin, fFst + fPeak + minVal, minVal + lPeak + lLast }); if (ans > INF) ans = -1; printf("%lld\n", ans); }