#include using namespace std; int INF = 1000000000; int main(){ int N; cin >> N; vector A(N); for (int i = 0; i < N; i++){ cin >> A[i]; } vector L1(N); L1[0] = A[0]; for (int i = 1; i < N; i++){ L1[i] = min(L1[i - 1], A[i]); } vector R1(N); R1[N - 1] = A[N - 1]; for (int i = N - 2; i >= 0; i--){ R1[i] = min(R1[i + 1], A[i]); } int ans1 = INF; for (int i = 1; i < N - 1; i++){ if (L1[i - 1] < A[i] && A[i] > R1[i + 1]){ ans1 = min(ans1, L1[i - 1] + A[i] + R1[i + 1]); } } vector L2(N); set L; for (int i = 0; i < N; i++){ auto itr = L.upper_bound(A[i]); if (itr == L.end()){ L2[i] = INF; } else { L2[i] = *itr; } L.insert(A[i]); } vector R2(N); set R; for (int i = N - 1; i >= 0; i--){ auto itr = R.upper_bound(A[i]); if (itr == R.end()){ R2[i] = INF; } else { R2[i] = *itr; } R.insert(A[i]); } int ans2 = INF; for (int i = 1; i < N - 1; i++){ ans2 = min(ans2, L2[i] + A[i] + R2[i]); } int ans = min(ans1, ans2); if (ans == INF){ cout << -1 << endl; } else { cout << ans << endl; } }