#include using namespace std; #define rep(i, n) for (int i = 0; i < (n); i++) #define ALL(v) (v).begin(), (v).end() using ll = long long; using P = pair; constexpr int INF = 1e9; constexpr long long LINF = 1e18; constexpr long long MOD = 1e9 + 7; signed main() { int n; cin >> n; int a[n]; rep(i, n) { cin >> a[i]; } int lsummn[n + 1], rsummn[n + 1], lsummx[n + 1], rsummx[n + 1]; lsummn[0] = INF; lsummx[0] = -INF; rep(i, n) { lsummn[i + 1] = min(lsummn[i], a[i]); lsummx[i + 1] = max(lsummx[i], a[i]); } reverse(a, a + n); rsummn[0] = INF; rsummx[0] = -INF; rep(i, n) { rsummn[i + 1] = min(rsummn[i], a[i]); rsummx[i + 1] = max(rsummx[i], a[i]); } reverse(a, a + n); int ans = INF; for (int i = 1; i < n - 1; i++) { if (lsummn[i] < a[i] && a[i] > rsummn[n - 1 - i]) { ans = min(ans, lsummn[i] + a[i] + rsummn[n - 1 - i]); } if (lsummx[i] > a[i] && a[i] < rsummx[n - 1 - i]) { ans = min(ans, lsummx[i] + a[i] + rsummx[n - 1 - i]); } } cout << (ans != INF ? ans : -1) << endl; return 0; }