#include #include #include #include bool judge(int a, int b, int c) { return ((a < b && b > c) || (a > b && b < c)); } constexpr int INF = 1 << 29; void solve() { int n; std::cin >> n; std::vector xs(n); for (auto& x : xs) std::cin >> x; std::vector lsmall(n, INF), lbig(n, INF), rsmall(n, INF), rbig(n, INF); { int lmin = INF; std::set s; for (int i = 0; i < n; ++i) { if (lmin < xs[i]) lsmall[i] = lmin; auto it = s.upper_bound(xs[i]); if (it != s.end()) lbig[i] = *it; lmin = std::min(lmin, xs[i]); s.insert(xs[i]); } } { int rmin = INF; std::set s; for (int i = n - 1; i >= 0; --i) { if (rmin < xs[i]) rsmall[i] = rmin; auto it = s.upper_bound(xs[i]); if (it != s.end()) rbig[i] = *it; rmin = std::min(rmin, xs[i]); s.insert(xs[i]); } } int ans = INF; for (int i = 0; i < n; ++i) { ans = std::min({ans, lsmall[i] + xs[i] + rsmall[i], lbig[i] + xs[i] + rbig[i]}); } std::cout << (ans == INF ? -1 : ans) << "\n"; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }