#include using namespace std; #ifdef LOCAL #include "debug.h" #else #define DEBUG(...) #endif template struct segtree { const int n; vector t; segtree(int _n = 0) : n(_n), t(2 * n) {} T& operator[](int i) { return t[n + i]; } void build() { for (int i = n; i--; ) t[i] = t[2 * i] * t[2 * i + 1]; } T fold(int l, int r) const { T a, b; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l & 1) a = a * t[l++]; if (r & 1) b = t[--r] * b; } return a * b; } void set(int i, T a) { t[i += n] = a; while (i >>= 1) t[i] = t[2 * i] * t[2 * i + 1]; } }; template constexpr T inf = numeric_limits::max() / 2.1; template struct mini { T v = inf; mini operator*(mini b) const { return b.v < v ? b : *this; } }; template struct maxi { T v = -inf; maxi operator*(maxi b) const { return v < b.v ? b : *this; } }; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; vector a(n); for (auto&& e : a) cin >> e; int res = inf; { vector ord(n); iota(begin(ord), end(ord), 0); sort(begin(ord), end(ord), [&](int i, int j) { return a[i] < a[j]; }); segtree> seg(n); for (int i : ord) { if (seg.fold(0, i).v != inf and seg.fold(i + 1, n).v != inf) { res = min(res, seg.fold(0, i).v + a[i] + seg.fold(i + 1, n).v); } seg.set(i, {a[i]}); } } { vector ord(n); iota(begin(ord), end(ord), 0); sort(begin(ord), end(ord), [&](int i, int j) { return a[i] > a[j]; }); segtree> seg(n); for (int i : ord) { if (seg.fold(0, i).v != inf and seg.fold(i + 1, n).v != inf) { res = min(res, seg.fold(0, i).v + a[i] + seg.fold(i + 1, n).v); } seg.set(i, {a[i]}); } } if (res == inf) { res = -1; } cout << res << '\n'; }