#pragma GCC optimize("O3") #include #define ll long long #define rep(i,n) for(ll i=0;i<(n);i++) #define pll pair #define pq priority_queue #define pb push_back #define eb emplace_back #define fi first #define se second #define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); #define lb(c,x) distance(c.begin(),lower_bound(all(c),x)) #define ub(c,x) distance(c.begin(),upper_bound(all(c),x)) using namespace std; template inline bool chmax(T& a,T b){if(a inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;} const ll INF=1e18; int main(){ ll n; cin >> n; vector a(n),maxle(n),maxri(n),minle(n),minri(n),maxxri(n); rep(i,n){ cin >> a[i]; } ll maxr=-1,maxl=-1,minr=INF,minl=INF; rep(i,n){ maxle[i]=maxl; maxl=max(maxl,a[i]); minle[i]=minl; minl=min(minl,a[i]); } for(ll i=n-1;i>=0;i--){ maxri[i]=maxr; maxr=max(maxr,a[i]); minri[i]=minr; minr=min(minr,a[i]); } maxxri=maxri; sort(maxxri.begin(),maxxri.end()); ll ans=INF; for(ll i=1;ia[i] && maxri[i]>a[i]){ ll le=i,ri=n; while(ri-le>1){ ll mid=(ri+le)/2; if(maxri[mid]>a[i]) ri=mid; else le=mid; } auto it=upper_bound(maxle.begin(),maxle.end(),a[i])-maxle.begin(); ll val1=maxle[it]; ll val2=maxri[ri]; ans=min(ans,val1+val2+a[i]); } if(minle[i]