#include using namespace std; using ll = long long; int main(){ cin.tie(nullptr); ios_base::sync_with_stdio(false); int N, ans=2e9, x, y; cin >> N; vector A(N+1); for(int i=1; i<=N; ++i) cin >> A[i]; set sl, sr; for (int i=1; i<=N; ++i) sr.insert(i); for (int i=1; i<=N; i++){ sr.erase(A[i]); if (sl.size() == 0 || sr.size() == 0){ sl.insert(A[i]); continue; } x = *sl.begin(); y = *sr.begin(); if (x < A[i] && y < A[i]) ans = min(ans, x+y+A[i]); x = *sl.rbegin(); y = *sr.rbegin(); if (x > A[i] && y > A[i]) ans = min(ans, x+y+A[i]); sl.insert(A[i]); } if (ans == 2e9) cout << -1; else cout << ans; cout << '\n'; return 0; }