#include <bits/stdc++.h>
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<int, int>;
constexpr int INF = 1e9;
constexpr long long LINF = 1e18;
constexpr long long MOD = 1e9 + 7;

signed main() {
    int n;
    cin >> n;
    ll a[n];
    rep(i, n) {
        cin >> a[i];
    }
    ll lsummn[n + 1], rsummn[n + 1], lsummx[n + 1], rsummx[n + 1];
    fill(lsummn, lsummn + n + 1, LINF);
    fill(lsummx, lsummx + n + 1, -LINF);
    fill(rsummn, rsummn + n + 1, LINF);
    fill(rsummx, rsummx + n + 1, -LINF);
    rep(i, n) {
        lsummn[i + 1] = min(lsummn[i], a[i]);
        lsummx[i + 1] = max(lsummx[i], a[i]);
    }
    reverse(a, a + n);
    rep(i, n) {
        rsummn[i + 1] = min(rsummn[i], a[i]);
        rsummx[i + 1] = max(rsummx[i], a[i]);
    }
    reverse(a, a + n);
    ll ans = LINF;
    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 != LINF ? ans : -1) << endl;
    return 0;
}