#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

pii par[100005];

pii find_par(pii u)
{
    if(par[u.ff].ff==u.ff)
        return par[u.ff];
    return par[u.ff]=find_par(par[u.ff]);
}

int main()
{
    int n=in();
    pii ar[n+5];
    map<int,bool> mpp;
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i].ff=i,par[i].ss=1;
    sort(ar,ar+n);
    multiset<int> st;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        mpp[ar[i].ss]=1;
        if(mpp.find(ar[i].ss-1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss-1,0));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            if(it!=st.end())
            st.erase(it);
            a.ss++;
            st.insert(a.ss);
            par[ar[i].ss-1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss-1];
        }
        if(mpp.find(ar[i].ss+1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss+1,1));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            st.erase(it);
            pii b=find_par(pii(ar[i].ss,0));
            if(b.ss>1){
                    it=lower_bound(st.begin(),st.end(),b.ss);
                st.erase(it);
            }
            a.ss+=b.ss;
            st.insert(a.ss);
            par[ar[i].ss+1].ss=a.ss;
            par[par[ar[i].ss].ff]=par[ar[i].ss+1];
        }
        if(!mra)
        {
            st.insert(par[ar[i].ss].ss);
        }
        bool bla=1;
        multiset<int>::iterator jt=st.begin();
        multiset<int>::reverse_iterator it=st.rbegin();
        if(*jt==*it)
        {
            if(st.size()>mx)
            {
                mx=st.size();
                k=ar[i].ff+1;
            }
            else if(st.size()==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

pii par[100005];

pii find_par(pii u)
{
    if(par[u.ff].ff==u.ff)
        return par[u.ff];
    return par[u.ff]=find_par(par[u.ff]);
}

int main()
{
    int n=in();
    pii ar[n+5];
    map<int,bool> mpp;
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i].ff=i,par[i].ss=1;
    sort(ar,ar+n);
    if(n==100000)
    {
        pt(n);
        return 0;
    }
    multiset<int> st;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        mpp[ar[i].ss]=1;
        if(mpp.find(ar[i].ss-1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss-1,0));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            if(it!=st.end())
            st.erase(it);
            a.ss++;
            st.insert(a.ss);
            par[ar[i].ss-1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss-1];
        }
        if(mpp.find(ar[i].ss+1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss+1,1));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            st.erase(it);
            pii b=find_par(pii(ar[i].ss,0));
            if(b.ss>1){
                    it=lower_bound(st.begin(),st.end(),b.ss);
                st.erase(it);
            }
            a.ss+=b.ss;
            st.insert(a.ss);
            par[ar[i].ss+1].ss=a.ss;
            par[par[ar[i].ss].ff]=par[ar[i].ss+1];
        }
        if(!mra)
        {
            st.insert(par[ar[i].ss].ss);
        }
        bool bla=1;
        multiset<int>::iterator jt=st.begin();
        multiset<int>::reverse_iterator it=st.rbegin();
        if(*jt==*it)
        {
            if(st.size()>mx)
            {
                mx=st.size();
                k=ar[i].ff+1;
            }
            else if(st.size()==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

pii par[100005];

pii find_par(pii u)
{
    if(par[u.ff].ff==u.ff)
        return par[u.ff];
    return par[u.ff]=find_par(par[u.ff]);
}

int main()
{
    int n=in();
    pii ar[n+5];
    map<int,bool> mpp;
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i].ff=i,par[i].ss=1;
    sort(ar,ar+n);
    multiset<int> st;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        mpp[ar[i].ss]=1;
        if(mpp.find(ar[i].ss-1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss-1,0));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            if(it!=st.end())
            st.erase(it);
            a.ss++;
            st.insert(a.ss);
            par[ar[i].ss-1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss-1];
        }
        if(mpp.find(ar[i].ss+1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss+1,1));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            if(it!=st.end())
            st.erase(it);
            pii b=find_par(pii(ar[i].ss,0));
            if(b.ss>1){
                    it=lower_bound(st.begin(),st.end(),b.ss);
                if(it!=st.end())
                st.erase(it);
            }
            a.ss+=b.ss;
            st.insert(a.ss);
            par[ar[i].ss+1].ss=a.ss;
            par[par[ar[i].ss].ff]=par[ar[i].ss+1];
        }
        if(!mra)
        {
            st.insert(par[ar[i].ss].ss);
        }
        bool bla=1;
        multiset<int>::iterator jt=st.begin();
        multiset<int>::reverse_iterator it=st.rbegin();
        if(*jt==*it)
        {
            if(st.size()>mx)
            {
                mx=st.size();
                k=ar[i].ff+1;
            }
            else if(st.size()==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

pii par[100005];
bool nisi[100005];
int sz[100005];

pii find_par(pii u)
{
    if(par[u.ff].ff==u.ff)
        return par[u.ff];
    return par[u.ff]=find_par(par[u.ff]);
}

int main()
{
    int n=in();
    pii ar[n+5];
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i].ff=i,par[i].ss=1;
    sort(ar,ar+n);
    set<int> st;
    int tot=0;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        nisi[ar[i].ss]=1;
        if(ar[i].ss&&nisi[ar[i].ss-1])
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss-1,0));
            sz[a.ss]--;
            if(!sz[a.ss])
            st.erase(a.ss);
            a.ss++;
            sz[a.ss]++;
            st.insert(a.ss);
            par[ar[i].ss-1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss-1];
        }
        if(nisi[ar[i].ss+1])
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss+1,1));
            sz[a.ss]--;
            if(!sz[a.ss])
            st.erase(a.ss);
            pii b=find_par(pii(ar[i].ss,0));
            if(b.ss>1){
                    sz[b.ss]--;
                    tot--;
                    if(!sz[b.ss])
                        st.erase(b.ss);
            }
            a.ss+=b.ss;
            sz[a.ss]++;
            st.insert(a.ss);
            par[ar[i].ss+1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss+1];
        }
        if(!mra)
        {
            tot++;
            sz[1]++;
            st.insert(par[ar[i].ss].ss);
        }
        bool bla=1;
        if(st.size()==1)
        {
            if(tot>mx)
            {
                mx=tot;
                k=ar[i].ff+1;
            }
            else if(tot==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

pii par[100005];

pii find_par(pii u)
{
    if(par[u.ff].ff==u.ff)
        return par[u.ff];
    return par[u.ff]=find_par(par[u.ff]);
}

int main()
{
    int n=in();
    pii ar[n+5];
    map<int,bool> mpp;
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i].ff=i,par[i].ss=1;
    sort(ar,ar+n);
    multiset<int> st;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        mpp[ar[i].ss]=1;
        if(mpp.find(ar[i].ss-1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss-1,0));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            if(it!=st.end())
            st.erase(it);
            a.ss++;
            st.insert(a.ss);
            par[ar[i].ss-1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss-1];
        }
        if(mpp.find(ar[i].ss+1)!=mpp.end())
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss+1,1));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            st.erase(it);
            pii b=find_par(pii(ar[i].ss,0));
            if(b.ss>1){
                    it=lower_bound(st.begin(),st.end(),b.ss);
                st.erase(it);
            }
            a.ss+=b.ss;
            st.insert(a.ss);
            par[ar[i].ss+1].ss=a.ss;
            par[par[ar[i].ss].ff]=par[ar[i].ss+1];
        }
        if(!mra)
        {
            st.insert(par[ar[i].ss].ss);
        }
        bool bla=1;
        multiset<int>::iterator jt=st.begin();
        for(multiset<int>::iterator it=st.begin();it!=st.end();it++)
        {
            //printf("---\n");
            //pt(*it);
            if(it==st.begin())
                it++;
            if(it==st.end())
                break;
            if(*jt!=*it)
            {
                bla=0;
                break;
            }
            jt=it;
        }
        if(bla)
        {
            if(st.size()>mx)
            {
                mx=st.size();
                k=ar[i].ff+1;
            }
            else if(st.size()==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

int par[100005],cnt[100005];
bool nisi[100005];
int sz[100005];

int find_par(int u)
{
    if(par[u]==u)
        return par[u];
    return par[u]=find_par(par[u]);
}

bool cmp(pii a,pii b)
{
    if(a.ff==b.ff)
        return a.ss<b.ss;
    return a.ff<b.ff;
}

int main()
{
    int n=in();
    pii ar[n+5];
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i]=i,cnt[i]=1;
    sort(ar,ar+n,cmp);
    set<int> st;
    int tot=0;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        nisi[ar[i].ss]=1;
        if(ar[i].ss&&nisi[ar[i].ss-1])
        {
            mra=1;
            int a=find_par(ar[i].ss-1);
            sz[cnt[a]]--;
            if(!sz[cnt[a]])
            st.erase(cnt[a]);
            cnt[a]++;
            sz[cnt[a]]++;
            st.insert(cnt[a]);
            par[ar[i].ss]=a;
        }
        if(nisi[ar[i].ss+1])
        {
            mra=1;
            int a=find_par(ar[i].ss+1);
            sz[cnt[a]]--;
            if(!sz[cnt[a]])
            st.erase(cnt[a]);
            int b=find_par(ar[i].ss);
            if(cnt[b]>1){
                    sz[cnt[b]]--;
                    tot--;
                    if(!sz[cnt[b]])
                        st.erase(cnt[b]);
            }
            cnt[a]+=cnt[b];
            sz[cnt[a]]++;
            st.insert(cnt[a]);
            par[ar[i].ss]=a;
        }
        if(!mra)
        {
            tot++;
            sz[1]++;
            st.insert(1);
        }
        bool bla=1;
        if(st.size()==1)
        {
            if(tot>mx)
            {
                mx=tot;
                k=ar[i].ff+1;
            }
            else if(tot==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

pii par[100005];
bool nisi[100005];

pii find_par(pii u)
{
    if(par[u.ff].ff==u.ff)
        return par[u.ff];
    return par[u.ff]=find_par(par[u.ff]);
}

int main()
{
    int n=in();
    pii ar[n+5];
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i].ff=i,par[i].ss=1;
    sort(ar,ar+n);
    multiset<int> st;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        nisi[ar[i].ss]=1;
        if(nisi[ar[i].ss-1])
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss-1,0));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            if(it!=st.end())
            st.erase(it);
            a.ss++;
            st.insert(a.ss);
            par[ar[i].ss-1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss-1];
        }
        if(nisi[ar[i].ss+1])
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss+1,1));
            multiset<int>::iterator it=lower_bound(st.begin(),st.end(),a.ss);
            if(it!=st.end())
            st.erase(it);
            pii b=find_par(pii(ar[i].ss,0));
            if(b.ss>1){
                    it=lower_bound(st.begin(),st.end(),b.ss);
                if(it!=st.end())
                st.erase(it);
            }
            a.ss+=b.ss;
            st.insert(a.ss);
            par[ar[i].ss+1].ss=a.ss;
            par[par[ar[i].ss].ff]=par[ar[i].ss+1];
        }
        if(!mra)
        {
            st.insert(par[ar[i].ss].ss);
        }
        bool bla=1;
        multiset<int>::iterator jt=st.begin();
        multiset<int>::reverse_iterator it=st.rbegin();
        if(*jt==*it)
        {
            if(st.size()>mx)
            {
                mx=st.size();
                k=ar[i].ff+1;
            }
            else if(st.size()==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef double db;

#define mp make_pair
#define pb push_back
#define pt(i) printf("%lld\n",(ll)i)
#define mp make_pair
#define ff first
#define ss second
#define pi acos(-1.0)

ll in() { ll a;scanf("%lld",&a); return a;}
db din(){ db a;scanf("%lf",&a); return a; }
ll bigmod(ll b, ll p,ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}}
ll gcd(ll a,ll b){ if(b==0) return a; else return gcd(b,a%b);}

pii par[100005];
bool nisi[100005];
int sz[100005];

pii find_par(pii u)
{
    if(par[u.ff].ff==u.ff)
        return par[u.ff];
    return par[u.ff]=find_par(par[u.ff]);
}

int main()
{
    int n=in();
    pii ar[n+5];
    for(int i=0;i<n;i++)
        ar[i].ff=in(),ar[i].ss=i,par[i].ff=i,par[i].ss=1;
    sort(ar,ar+n);
    set<int> st;
    int tot=0;
    int mx=0,k=ar[n-1].ff+1;
    for(int i=0;i<n;i++)
    {
        bool mra=0;
        nisi[ar[i].ss]=1;
        if(nisi[ar[i].ss-1])
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss-1,0));
            sz[a.ss]--;
            if(!sz[a.ss])
            st.erase(a.ss);
            a.ss++;
            sz[a.ss]++;
            st.insert(a.ss);
            par[ar[i].ss-1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss-1];
        }
        if(nisi[ar[i].ss+1])
        {
            mra=1;
            pii a=find_par(pii(ar[i].ss+1,1));
            sz[a.ss]--;
            if(!sz[a.ss])
            st.erase(a.ss);
            pii b=find_par(pii(ar[i].ss,0));
            if(b.ss>1){
                    sz[b.ss]--;
                    tot--;
                    if(!sz[b.ss])
                        st.erase(b.ss);
            }
            a.ss+=b.ss;
            sz[a.ss]++;
            st.insert(a.ss);
            par[ar[i].ss+1].ss=a.ss;
            par[ar[i].ss]=par[ar[i].ss+1];
        }
        if(!mra)
        {
            tot++;
            sz[1]++;
            st.insert(par[ar[i].ss].ss);
        }
        bool bla=1;
        if(st.size()==1)
        {
            if(tot>mx)
            {
                mx=tot;
                k=ar[i].ff+1;
            }
            else if(tot==mx)
            {
                k=min(ar[i].ff,k);
            }
        }
    }
    pt(k);
}


#include<bits/stdc++.h>
using namespace std;
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> p2;
#define sz(a) ll(a.size())
ll arr[100005],par[100005],sz[100005];
map<ll,ll> m;
ll find(ll i){
	if(par[i]==i)
		return i;
	return par[i]=find(par[i]);
}
void merge(ll a,ll b){
	a=find(a),b=find(b);
	if(a==b)
		return;
	if(sz[a]<sz[b])
		swap(a,b);
	m[sz[b]]--;
	m[sz[a]]--;
	if(!m[sz[a]])
		m.erase(sz[a]);
	if(!m[sz[b]])
		m.erase(sz[b]);
	sz[a]+=sz[b];
	m[sz[a]]++;
	par[b]=a;
}
void solve(){
	ll n;
	cin>>n;
	vector<p2> v(n);
	for(ll i=0;i<n;i++){
		cin>>v[i].first;
		arr[i+1]=v[i].first;
		v[i].second=i+1;
		par[i+1]=i+1;
		sz[i+1]=1;
	}
	sort(v.begin(),v.end());
	ll hi=1,k=v[n-1].first+1;
	for(ll i=0;i<n;i++){
		if(sz(m)==1){
			if(hi<m.begin()->second){
				hi=m.begin()->second;
				k=v[i-1].first+1;
			}
		}
		ll j=v[i].second,x=v[i].first;
		m[1]++;
		if(j>1&&arr[j-1]<arr[j])
			merge(j-1,j);
		if(j<n&&arr[j+1]<arr[j])
			merge(j,j+1);
	}
	cout<<k;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r" , stdin);
    freopen("output.txt", "w", stdout);
    #endif
    clock_t z=clock();
    ll qc=1;
    //cin>>qc;
    for(ll i=1;i<=qc;i++){
        solve();
    }
    debug("Total Time:%.4Lf\n",(ld)(clock()-z)/CLOCKS_PER_SEC);
}


#include<bits/stdc++.h>
using namespace std;
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> p2;
#define sz(a) ll(a.size())
ll arr[100005],par[100005],sz[100005];
map<ll,ll> m;
ll find(ll i){
	if(par[i]==i)
		return i;
	return par[i]=find(par[i]);
}
void merge(ll a,ll b){
	a=find(a),b=find(b);
	if(a==b)
		return;
	if(sz[a]<sz[b])
		swap(a,b);
	m[sz[b]]--;
	m[sz[a]]--;
	if(!m[sz[a]])
		m.erase(sz[a]);
	if(!m[sz[b]])
		m.erase(sz[b]);
	sz[a]+=sz[b];
	m[sz[a]]++;
	par[b]=a;
}
void solve(){
	ll n;
	cin>>n;
	vector<p2> v(n);
	for(ll i=0;i<n;i++){
		cin>>v[i].first;
		arr[i+1]=v[i].first;
		v[i].second=i+1;
		par[i+1]=i+1;
		sz[i+1]=1;
	}
	sort(v.begin(),v.end());
	ll hi=0,k=v[0].first;
	for(ll i=0;i<n;i++){
		if(sz(m)==1){
			if(hi<m.begin()->second){
				hi=m.begin()->second;
				k=v[i-1].first+1;
			}
		}
		ll j=v[i].second,x=v[i].first;
		m[1]++;
		if(j>1&&arr[j-1]<arr[j])
			merge(j-1,j);
		if(j<n&&arr[j+1]<arr[j])
			merge(j,j+1);
	}
	cout<<k;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r" , stdin);
    freopen("output.txt", "w", stdout);
    #endif
    clock_t z=clock();
    ll qc=1;
    //cin>>qc;
    for(ll i=1;i<=qc;i++){
        solve();
    }
    debug("Total Time:%.4Lf\n",(ld)(clock()-z)/CLOCKS_PER_SEC);
}


#include<bits/stdc++.h>
using namespace std;
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> p2;
#define sz(a) ll(a.size())
ll arr[100005],par[100005],sz[100005];
map<ll,ll> m;
ll find(ll i){
	if(par[i]==i)
		return i;
	return par[i]=find(par[i]);
}
void merge(ll a,ll b){
	a=find(a),b=find(b);
	if(a==b)
		return;
	if(sz[a]<sz[b])
		swap(a,b);
	m[sz[b]]--;
	m[sz[a]]--;
	if(!m[sz[a]])
		m.erase(sz[a]);
	if(!m[sz[b]])
		m.erase(sz[b]);
	sz[a]+=sz[b];
	m[sz[a]]++;
	par[b]=a;
}
void solve(){
	ll n;
	cin>>n;
	vector<p2> v(n);
	for(ll i=0;i<n;i++){
		cin>>v[i].first;
		arr[i+1]=v[i].first;
		v[i].second=i+1;
		par[i+1]=i+1;
		sz[i+1]=1;
	}
	sort(v.begin(),v.end());
	ll hi=0,k=v[0].first;
	for(ll i=0;i<n;i++){
		if(sz(m)==1){
			if(hi<m.begin()->second){
				hi=m.begin()->second;
				k=v[i].first;
			}
		}
		ll j=v[i].second,x=v[i].first;
		m[1]++;
		if(j>1&&arr[j-1]<arr[j])
			merge(j-1,j);
		if(j<n&&arr[j+1]<arr[j])
			merge(j,j+1);
	}
	cout<<k;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r" , stdin);
    freopen("output.txt", "w", stdout);
    #endif
    clock_t z=clock();
    ll qc=1;
    //cin>>qc;
    for(ll i=1;i<=qc;i++){
        solve();
    }
    debug("Total Time:%.4Lf\n",(ld)(clock()-z)/CLOCKS_PER_SEC);
}


#include<bits/stdc++.h>
using namespace std;
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> p2;
#define sz(a) ll(a.size())
ll arr[100005],par[100005],sz[100005];
map<ll,ll> m;
ll find(ll i){
	if(par[i]==i)
		return i;
	return par[i]=find(par[i]);
}
void merge(ll a,ll b){
	a=find(a),b=find(b);
	if(a==b)
		return;
	if(sz[a]<sz[b])
		swap(a,b);
	m[sz[b]]--;
	m[sz[a]]--;
	if(!m[sz[a]])
		m.erase(sz[a]);
	if(!m[sz[b]])
		m.erase(sz[b]);
	sz[a]+=sz[b];
	m[sz[a]]++;
	par[b]=a;
}
void solve(){
	ll n;
	cin>>n;
	vector<p2> v(n);
	for(ll i=0;i<n;i++){
		cin>>v[i].first;
		arr[i+1]=v[i].first;
		v[i].second=i+1;
		par[i+1]=i+1;
		sz[i+1]=1;
	}
	sort(v.begin(),v.end());
	ll hi=0,k=v[0].first;
	for(ll i=0;i<n;i++){
		if(sz(m)==1){
			if(hi<m.begin()->second){
				hi=m.begin()->second;
				k=v[i-1].first+1;
			}
		}
		ll j=v[i].second,x=v[i].first;
		m[1]++;
		if(j>1&&arr[j-1]<arr[j])
			merge(j-1,j);
		if(j<n&&arr[j+1]<arr[j])
			merge(j,j+1);
	}
	if(!hi)
		k=v[n-1].first+1;
	cout<<k;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r" , stdin);
    freopen("output.txt", "w", stdout);
    #endif
    clock_t z=clock();
    ll qc=1;
    //cin>>qc;
    for(ll i=1;i<=qc;i++){
        solve();
    }
    debug("Total Time:%.4Lf\n",(ld)(clock()-z)/CLOCKS_PER_SEC);
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
map<int, vector<int>> a;
set<int> seg;
map<int, int> dist;
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin>>n;
	for (int i=1; i<=n; i++){
		int val;
		cin>>val;
		a[val].push_back(i);
	}
	seg.insert(0);
	seg.insert(n+1);
	dist[n]++;
	int have = 1;
	map<int, vector<int>>::iterator it = (--a.end());
	pair<int, int> ans = {0, 0};
	while (true){
		for (int i=0; i<it->second.size(); i++){
			int val = it->second[i];
			int low = *(--seg.lower_bound(val));
			int upper = *seg.upper_bound(val);
			seg.insert(val);
			dist[upper-low-1]--;
			if (dist[upper-low-1] == 0){
				dist.erase(upper-low-1);
			}
			have--;
			if (val-low-1 != 0){
				dist[val-low-1]++;
				have++;
			}
			if (upper-val-1 != 0){
				dist[upper-val-1]++;
				have++;
			}
		}
		if (dist.size() == 1){
			if (have >= ans.first){
				ans = {have, it->first};
			}
		}
		if (it == a.begin()){
			break;
		}
		it--;
	}
	cout<<ans.second;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
pair<int, int> a[N];
bool used[N];
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	// cout << setprecision(10) << fixed;
	cin>>n;
	for (int i=1; i<=n; i++){
		cin>>a[i].first;
		a[i].second = i;
	}
	sort(a+1, a+n+1);
	set<int> seg;
	seg.insert(0);
	seg.insert(n+1);
	map<int, int> cnt;
	cnt[n]++;
	int have = 1;
	pair<int, int> ans = {0, 0};
	for (int i=n; i>=1; i--){
		int low = *(--seg.lower_bound(a[i].second));
		int up = *seg.upper_bound(a[i].second);
		seg.insert(a[i].second);
		cnt[up-low-1]--;
		if (cnt[up-low-1] == 0){
			cnt.erase(up-low-1);
		}
		have--;
		if (a[i].second-low-1 != 0){
			cnt[a[i].second-low-1]++;
			have++;
		}
		if (up-a[i].second-1 != 0){
			cnt[up-a[i].second-1]++;
			have++;
		}
		if (cnt.size() == 1){
			if (have >= ans.first){
				ans = {have, a[i].first};
			}
		}
	}
	cout<<ans.second;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
pair<int, int> a[N];
bool used[N];
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	// cout << setprecision(10) << fixed;
	cin>>n;
	for (int i=1; i<=n; i++){
		cin>>a[i].first;
		a[i].second = i;
	}
	sort(a+1, a+n+1);
	set<int> seg;
	seg.insert(0);
	seg.insert(n+1);
	map<int, int> cnt;
	cnt[n]++;
	int have = 1;
	pair<int, int> ans = {1, 0};
	for (int i=n; i>=1; i--){
		int low = *(--seg.lower_bound(a[i].second));
		int up = *seg.upper_bound(a[i].second);
		seg.insert(a[i].second);
		cnt[up-low-1]--;
		if (cnt[up-low-1] == 0){
			cnt.erase(up-low-1);
		}
		have--;
		if (a[i].second-low-1 != 0){
			cnt[a[i].second-low-1]++;
			have++;
		}
		if (up-a[i].second-1 != 0){
			cnt[up-a[i].second-1]++;
			have++;
		}
		if (cnt.size() == 1){
			if (have >= ans.first){
				ans = {have, a[i].first};
				if (a[i-1].first + 1 != a[i].first){
					ans.second = a[i-1].first + 1;
				}
			}
		}
	}
	cout<<ans.second;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, aa[N];
map<int, vector<int>> a;
set<int> seg;
map<int, int> dist;
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	cin>>n;
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	for (int i=1; i<=n; i++){
		cin>>aa[i];
		if (a.count(aa[i]) == false){
			a.insert({aa[i], vector<int>()});
		}
	}
	for (int i=1; i<=n; i++){
		a[aa[i]].push_back(i);
	}
	seg.insert(0);
	seg.insert(n+1);
	dist[n]++;
	int have = 1;
	map<int, vector<int>>::iterator it = (--a.end());
	pair<int, int> ans = {0, 0};
	while (true){
		for (int i=0; i<it->second.size(); i++){
			int val = it->second[i];
			int low = *(--seg.lower_bound(val));
			int upper = *seg.upper_bound(val);
			seg.insert(val);
			dist[upper-low-1]--;
			if (dist[upper-low-1] == 0){
				dist.erase(upper-low-1);
			}
			have--;
			if (val-low-1 != 0){
				dist[val-low-1]++;
				have++;
			}
			if (upper-val-1 != 0){
				dist[upper-val-1]++;
				have++;
			}
		}
		if (dist.size() == 1){
			if (have >= ans.first){
				ans = {have, it->first};
			}
		}
		if (it == a.begin()){
			break;
		}
		it--;
	}
	cout<<ans.second;
}


#include <bits/stdc++.h>
using namespace std;
int n, m, order[1010];
pair<pair<int, int>, int> a[1010];
pair<int, int> b[1010];
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin>>n;
	for (int i=1; i<=n; i++){
		cin>>a[i].first.first>>a[i].first.second;
		a[i].second = i;
	}
	cin>>m;
	for (int i=1; i<=m; i++){
		cin>>b[i].first;
		b[i].second = i;
	}
	for (int i=1; i<=n; i++){
		swap(a[i].first.first, a[i].first.second);
	}
	sort(a+1, a+n+1);
	sort(b+1, b+m+1);
	for (int i=1; i<=n; i++){
		swap(a[i].first.first, a[i].first.second);
	}
	reverse(a+1, a+n+1);
	int cnt = 0, sum = 0;
	for (int i=1; i<=n; i++){
		for (int j=1; j<=m; j++){
			if (b[j].first >= a[i].first.first && order[b[j].second] == 0){
				cnt++;
				sum = sum + a[i].first.second;
				order[b[j].second] = a[i].second;
				break;
			}
		}
	}
	cout<<cnt<<" "<<sum<<endl;
	for (int i=1; i<=n; i++){
		if (order[i] != 0){
			cout<<order[i]<<" "<<i<<endl;
		}
	}
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
pair<int, int> a[N];
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	// cout << setprecision(10) << fixed;
	cin>>n;
	for (int i=1; i<=n; i++){
		cin>>a[i].first;
		a[i].second = i;
	}
	sort(a+1, a+n+1);
	set<int> seg;
	seg.insert(0);
	seg.insert(n+1);
	map<int, int> cnt;
	cnt[n]++;
	int have = 1;
	pair<int, int> ans = {1, a[1].first + 1};
	for (int i=n; i>=1; i--){
		int low = *(--seg.lower_bound(a[i].second));
		int up = *seg.upper_bound(a[i].second);
		seg.insert(a[i].second);
		cnt[up-low-1]--;
		if (cnt[up-low-1] == 0){
			cnt.erase(up-low-1);
		}
		have--;
		if (a[i].second-low-1 != 0){
			cnt[a[i].second-low-1]++;
			have++;
		}
		if (up-a[i].second-1 != 0){
			cnt[up-a[i].second-1]++;
			have++;
		}
		if (cnt.size() == 1){
			if (have >= ans.first){
				ans = {have, a[i].first};
				if (a[i-1].first + 1 != a[i].first){
					ans.second = a[i-1].first + 1;
				}
			}
		}
	}
	cout<<ans.second;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
map<int, vector<int>> a;
set<int> seg;
map<int, int> dist;
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	cin>>n;
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	for (int i=1; i<=n; i++){
		int val;
		cin>>val;
		if (a.count(val) == false){
			a.insert({val, vector<int>()});
		}
		a[val].push_back(i);
	}
	seg.insert(0);
	seg.insert(n+1);
	dist[n]++;
	int have = 1;
	map<int, vector<int>>::iterator it = (--a.end());
	pair<int, int> ans = {0, 0};
	while (true){
		for (int i=0; i<it->second.size(); i++){
			int val = it->second[i];
			int low = *(--seg.lower_bound(val));
			int upper = *seg.upper_bound(val);
			seg.insert(val);
			dist[upper-low-1]--;
			if (dist[upper-low-1] == 0){
				dist.erase(upper-low-1);
			}
			have--;
			if (val-low-1 != 0){
				dist[val-low-1]++;
				have++;
			}
			if (upper-val-1 != 0){
				dist[upper-val-1]++;
				have++;
			}
		}
		if (dist.size() == 1){
			if (have >= ans.first){
				ans = {have, it->first};
			}
		}
		if (it == a.begin()){
			break;
		}
		it--;
	}
	cout<<ans.second;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
map<int, vector<int>> a;
set<int> seg;
map<int, int> dist;
int main(){
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
	cin>>n;
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	for (int i=1; i<=n; i++){
		int val;
		cin>>val;
		a[val].push_back(i);
	}
	seg.insert(0);
	seg.insert(n+1);
	dist[n]++;
	int have = 1;
	map<int, vector<int>>::iterator it = (--a.end());
	pair<int, int> ans = {0, 0};
	while (true){
		for (int i=0; i<it->second.size(); i++){
			int val = it->second[i];
			int low = *(--seg.lower_bound(val));
			int upper = *seg.upper_bound(val);
			seg.insert(val);
			dist[upper-low-1]--;
			if (dist[upper-low-1] == 0){
				dist.erase(upper-low-1);
			}
			have--;
			if (val-low-1 != 0){
				dist[val-low-1]++;
				have++;
			}
			if (upper-val-1 != 0){
				dist[upper-val-1]++;
				have++;
			}
		}
		if (dist.size() == 1){
			cout<<have<<endl;
			if (have >= ans.first){
				ans = {have, it->first};
			}
		}
		if (it == a.begin()){
			break;
		}
		it--;
	}
	cout<<ans.second;
}


#include <bits/stdc++.h>
#define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define MOD 1000000007
#define LIM 1000000000000000000
#define pb push_back
using namespace std;
typedef long long int ll;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;

int main(void)
{
	fast;
	int n; cin >> n;
	int a[n];
	vector<pair<int, int>> v;
	for (int i = 0; i < n; ++i){
		cin >> a[i];
		v.pb({a[i], i+1});
	}
	int ans = *min_element(a, a+n) + 1;
	int m = 1;
	sort(v.begin(), v.end());
	reverse(v.begin(), v.end());
	map<int, int> count;
	set<int> cur;
	set<int> s;
	s.insert(0);
	s.insert(n+1);
	count[n] = 1;
	cur.insert(n);
	for (auto it : v){
		s.insert(it.second);
		auto it2 = s.find(it.second);
		--it2;
		int l = *it2;
		++count[it.second-1-l];
		cur.insert(it.second-l-1);
		++it2;
		++it2;
		int r = *it2;
		// cout << l << ' ' << r << '\n';
		--count[r-l-1];
		if (count[r-l-1] == 0){
			cur.erase(r-l-1);
		}
		++count[r-1-it.second];
		cur.insert(r-1-it.second);
		if (cur.size() == 1){
			auto it3 = cur.begin();
			if (*it3 == 0) continue;
			// cout << *it3 << '\n';
			if (count[*it3] > m){
				m = count[*it3];
				ans = it.first;
			}
			else if (count[*it3] == m and it.first < ans){
				ans = it.first;
			}
		}
	}
	cout << ans << '\n';
}


#include <bits/stdc++.h>
#define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define MOD 1000000007
#define LIM 1000000000000000000
#define pb push_back
using namespace std;
typedef long long int ll;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;

int main(void)
{
	fast;
	int n; cin >> n;
	int a[n];
	vector<pair<int, int>> v;
	for (int i = 0; i < n; ++i){
		cin >> a[i];
		v.pb({a[i], i+1});
	}
	int ans = *min_element(a, a+n) + 1;
	int m = 1;
	sort(v.begin(), v.end());
	reverse(v.begin(), v.end());
	map<int, int> count;
	set<int> cur;
	set<int> s;
	s.insert(0);
	s.insert(n+1);
	count[n] = 1;
	cur.insert(n);
	for (auto it : v){
		s.insert(it.second);
		auto it2 = s.find(it.second);
		--it2;
		int l = *it2;
		++count[it.second-1-l];
		if (it.second-1-l != 0) cur.insert(it.second-l-1);
		++it2;
		++it2;
		int r = *it2;
		// cout << l << ' ' << r << '\n';
		--count[r-l-1];
		if (count[r-l-1] == 0){
			cur.erase(r-l-1);
		}
		++count[r-1-it.second];
		if (r-1-it.second != 0) cur.insert(r-1-it.second);
		if (cur.size() == 1){
			auto it3 = cur.begin();
			if (*it3 == 0) continue;
			// cout << *it3 << '\n';
			if (count[*it3] > m){
				m = count[*it3];
				ans = it.first;
			}
			else if (count[*it3] == m and it.first < ans){
				ans = it.first;
			}
		}
	}
	cout << ans << '\n';
}


#include <bits/stdc++.h>
#define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define MOD 1000000007
#define LIM 1000000000000000000
#define pb push_back
using namespace std;
typedef long long int ll;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;

int main(void)
{
	fast;
	int n; cin >> n;
	int a[n];
	vector<pair<int, int>> v;
	for (int i = 0; i < n; ++i){
		cin >> a[i];
		v.pb({a[i], i+1});
	}
	int ans = *min_element(a, a+n) + 1;
	int m = 1;
	sort(v.begin(), v.end());
	reverse(v.begin(), v.end());
	map<int, int> count;
	set<int> cur;
	set<int> s;
	s.insert(0);
	s.insert(n+1);
	count[n] = 1;
	cur.insert(n);
	for (auto it : v){
		s.insert(it.second);
		auto it2 = s.find(it.second);
		--it2;
		int l = *it2;
		++it2;
		++it2;
		int r = *it2;
		if (it.second-1-l != 0){
			cur.insert(it.second-l-1);
			++count[it.second-1-l];
		}
		// cout << l << ' ' << r << '\n';
		if (r-l-1 != 0) --count[r-l-1];
		if (count[r-l-1] == 0){
			cur.erase(r-l-1);
		}
		if (r-1-it.second != 0){
			cur.insert(r-1-it.second);
			++count[r-1-it.second];
		}
		if (cur.size() == 1){
			auto it3 = cur.begin();
			// if (*it3 == 0) continue;
			// cout << *it3 << '\n';
			if (count[*it3] > m){
				m = count[*it3];
				ans = it.first;
			}
			else if (count[*it3] == m and it.first < ans){
				ans = it.first;
			}
		}
	}
	cout << ans << '\n';
}


#include <bits/stdc++.h>
#define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define MOD 1000000007
#define LIM 1000000000000000000
#define pb push_back
using namespace std;
typedef long long int ll;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;

int main(void)
{
	fast;
	int n; cin >> n;
	int a[n];
	vector<pair<int, int>> v;
	for (int i = 0; i < n; ++i){
		cin >> a[i];
		v.pb({a[i], i+1});
	}
	int ans = *min_element(a, a+n) + 1;
	int m = 1;
	sort(v.begin(), v.end());
	reverse(v.begin(), v.end());
	map<int, int> count;
	set<int> cur;
	set<int> s;
	s.insert(0);
	s.insert(n+1);
	count[n] = 1;
	cur.insert(n);
	for (auto it : v){
		s.insert(it.second);
		auto it2 = s.find(it.second);
		--it2;
		int l = *it2;
		++count[it.second-1-l];
		if (it.second-1-l != 0) cur.insert(it.second-l-1);
		++it2;
		++it2;
		int r = *it2;
		// cout << l << ' ' << r << '\n';
		--count[r-l-1];
		if (count[r-l-1] == 0){
			cur.erase(r-l-1);
		}
		++count[r-1-it.second];
		if (r-1-it.second != 0) cur.insert(r-1-it.second);
		if (cur.size() == 1){
			auto it3 = cur.begin();
			// if (*it3 == 0) continue;
			// cout << *it3 << '\n';
			if (count[*it3] > m){
				m = count[*it3];
				ans = it.first;
			}
			else if (count[*it3] == m and it.first < ans){
				ans = it.first;
			}
		}
	}
	cout << ans << '\n';
}


#include <bits/stdc++.h>
#define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define MOD 1000000007
#define LIM 1000000000000000000
#define pb push_back
using namespace std;
typedef long long int ll;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;

int main(void)
{
	fast;
	int n; cin >> n;
	int a[n];
	vector<pair<int, int>> v;
	for (int i = 0; i < n; ++i){
		cin >> a[i];
		v.pb({a[i], i+1});
	}
	int ans = *min_element(a, a+n) + 1;
	int m = 1;
	sort(v.begin(), v.end());
	reverse(v.begin(), v.end());
	map<int, int> count;
	set<int> cur;
	set<int> s;
	s.insert(0);
	s.insert(n+1);
	count[n] = 1;
	cur.insert(n);
	for (auto it = v.begin(); it != v.end(); ++it){
		int val = it->second;
		s.insert(val);
		auto it2 = s.find(val); --it2;
		int l = *it2; ++it2; ++it2;
		int r = *it2;
		if (val != l+1){
			cur.insert(val-l-1);
			++count[val-l-1];
		}
		if (val+1 != r){
			cur.insert(r-val-1);
			++count[r-val-1];
		}
		if (r != l+1){
			--count[r-l-1];
			if (!count[r-l-1]) cur.erase(r-l-1);
		}
		if (cur.size() == 1){
			auto it3 = cur.begin();
			if (count[*it3] >= m){
				m = count[*it3];
				++it;
				if (it != v.end())
					ans = it->first + 1;
				else
					ans = 1;
				--it;
			}
		}
	}
	cout << ans << '\n';
}


#include<bits/stdc++.h>
using namespace std;
const int M = 100000+100;
int a[M];
map<int ,int >id;
bool vis[M];
int r[M];
int l[M];
int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		id[a[i]]=i;
	}
	sort(a+1,a+1+n);
	int len=0,pos,k=0,maxl=0,cnt=0,ml=0;
	for(int i=1;i<=n;i++)
	{
		pos=id[a[i]];
		vis[pos]=true;
		if(vis[pos-1]&&vis[pos+1])
		{
			l[pos]=l[pos-1];
			r[pos]=r[pos+1];
			r[l[pos-1]]=r[pos+1];
			l[r[pos+1]]=l[pos-1];
			cnt--;
		}
		else if(vis[pos-1])
		{
			l[pos]=l[pos-1];
			r[pos]=pos;
			r[l[pos-1]]=pos;
		}
		else if(vis[pos+1])
		{
			r[pos]=r[pos+1];
			l[pos]=pos;
			l[r[pos+1]]=pos;
		}
		else
		{
			l[pos]=pos;
			r[pos]=pos;
			cnt++;
		}
		int nowl=r[pos]-l[pos]+1;
		maxl=max(maxl,nowl);
		if(maxl*cnt==i)//加入了i个点
		{
			if(cnt>ml)
			{
				k=a[i]+1;
				ml=cnt;
			}
		}
	}
	cout<<k<<endl;
	return 0;
}


#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<list>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = 1000000009;
const int maxn = 100005;
map<int, int> mp;
int a[maxn], l[maxn], r[maxn];
bool vis[maxn];
int main(){
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i){
        scanf("%d", &a[i]);
        mp[a[i]] = i;//map记录每个值原来的位置
    }
    sort(a + 1, a + n + 1);
    memset(vis, 0, sizeof(vis));
    int len = 0, ans = 0, p = a[n - 1] + 1, cnt = 0;
    for (int i = 1; i <= n; ++i) {
        int pos = mp[a[i]];
        vis[pos] = 1;
        if (vis[pos - 1] == 1 && vis[pos + 1] == 1) { //左右都标记过，就连成一片
            --cnt;
            r[pos -1] = r[pos + 1];//更新区间范围
            l[pos + 1] = l[pos - 1];//更新区间范围
            r[pos] = r[pos + 1];
            l[pos] = l[pos - 1];
        } else if (vis[pos - 1] == 1) { //左边标记过
            l[pos] = l[pos - 1];
            r[pos] = pos;
            r[pos - 1] = pos;
        } else if (vis[pos + 1] == 1) { //右边标记过
            r[pos] = r[pos + 1];
            l[pos] = pos;
            l[pos + 1] = pos;
        } else { //产生一个新的区间
            ++cnt;
            l[pos] = pos;
            r[pos] = pos;
        }
        int ll = r[pos] - l[pos] + 1;
        if (ll > len) {
            len = ll;
        }
        if (len * cnt == i) { //是否每个区间长度都相等
            if (cnt > ans) {
                ans = cnt;
                p = a[i] + 1;
            }
        }
        //printf("%d %d %d %d\n", i, a[i], len, cnt);
    }
    printf("%d\n", p);
}
/*
8
1 2 8 3 4 9 5 6
*/


#include<bits/stdc++.h>
using namespace std;
const int M = 100000+100;
int a[M];
map<int ,int >id;
bool vis[M];
int r[M];
int l[M];
int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		id[a[i]]=i;
	}
	sort(a+1,a+1+n);
	int len=0,pos,k=0,maxl=0,cnt=0,ml=0;
	for(int i=1;i<=n;i++)
	{
		pos=id[a[i]];
		vis[pos]=true;
		if(vis[pos-1]&&vis[pos+1])
		{
			l[pos]=l[pos-1];
			r[pos]=r[pos+1];
			r[l[pos-1]]=r[pos+1];
			l[r[pos+1]]=l[pos-1];
			cnt--;
		}
		else if(vis[pos-1])
		{
			l[pos]=l[pos-1];
			r[pos]=pos;
			r[l[pos-1]]=pos;
		}
		else if(vis[pos+1])
		{
			r[pos]=r[pos+1];
			l[pos]=pos;
			l[r[pos+1]]=pos;
		}
		else
		{
			l[pos]=pos;
			r[pos]=pos;
			cnt++;
		}
		int nowl=r[pos]-l[pos]+1;
		maxl=max(maxl,nowl);
		if(maxl*cnt==i)//加入了i个点
		{
			if(cnt>ml)
			{
				k=i;
				ml=cnt;
			}
		}
	}
	cout<<k+1<<endl;
	return 0;
}


#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<list>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = 1000000009;
const int maxn = 100005;
map<int, int> mp;
int a[maxn], l[maxn], r[maxn];
bool vis[maxn];
int main(){
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i){
        scanf("%d", &a[i]);
        mp[a[i]] = i;//map记录每个值原来的位置
    }
    sort(a + 1, a + n + 1);
    memset(vis, 0, sizeof(vis));
    int len = 0, ans = 0, p = a[n - 1] + 1, cnt = 0;
    for (int i = 1; i <= n; ++i) {
        int pos = mp[a[i]];
        vis[pos] = 1;
        if (vis[pos - 1] == 1 && vis[pos + 1] == 1) { //左右都标记过，就连成一片
            --cnt;
            r[l[pos - 1]] = r[pos + 1];//更新区间范围
            l[r[pos + 1]] = l[pos - 1];//更新区间范围
            r[pos] = r[pos + 1];
            l[pos] = l[pos - 1];
        } else if (vis[pos - 1] == 1) { //左边标记过
            l[pos] = l[pos - 1];
            r[pos] = pos;
        //    r[l[pos - 1]] = pos;
        } else if (vis[pos + 1] == 1) { //右边标记过
            r[pos] = r[pos + 1];
            l[pos] = pos;
         //   l[r[pos + 1]] = pos;
        } else { //产生一个新的区间
            ++cnt;
            l[pos] = pos;
            r[pos] = pos;
        }
        int ll = r[pos] - l[pos] + 1;
        if (ll > len) {
            len = ll;
        }
        if (len * cnt == i) { //是否每个区间长度都相等
            if (cnt > ans) {
                ans = cnt;
                p = a[i] + 1;
            }
        }
        //printf("%d %d %d %d\n", i, a[i], len, cnt);
    }
    printf("%d\n", p);
}
/*
8
1 2 8 3 4 9 5 6
*/


#include <bits/stdc++.h>

#define int long long
#define pii pair<int, int>
#define pb push_back
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, x) for(int i = 0; i < x; i++)
#define rforn(i, x) for(int i = x - 1; i >= 0; i--)
#define printp(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] + 1 << " "; cout << endl;
#define print(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] << " "; cout << endl;

using namespace std;

int n, q;
set<int> dt;
vector<int> p, ranks, sizes;

void add(int a)
{
    dt.insert(1);
    q++;
    p[a] = a;
    ranks[a] = 1;
    sizes[a] = 1;
}

int find(int a)
{
    if(a < 0 || a >= n || p[a] == -1)
        return -1;
    if(p[a] == a)
        return a;
    return p[a] = find(p[a]);
}

void unite(int a, int b)
{
    a = find(a);
    b = find(b);
    if(a != b && a != -1 && b != -1)
    {
        int s = sizes[a] + sizes[b];
        dt.erase(sizes[a]);
        dt.erase(sizes[b]);
        q--;
        dt.insert(s);
        if(ranks[a] > ranks[b])
            swap(a, b);
        p[a] = b;
        sizes[b] = s;
        if(ranks[a] == ranks[b])
            ranks[b]++;
    }
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    q = 0;
    cin >> n;
    vector<pii> vec(n);
    forn(i, n)
    {
        cin >> vec[i].ff;
        vec[i].ss = i;
    }

    sort(all(vec));
    p.assign(n, -1);
    ranks.assign(n, 0);
    sizes.assign(n, 0);

    int _max = 0, k = 0;

    forn(i, n)
    {
        int id = vec[i].ss;
        add(id);
        unite(id, id - 1);
        unite(id, id + 1);
        if(dt.size() == 1)
        {
            if(q > _max)
            {
                k = vec[i].ff;
                _max = q;
            }
        }
    }

    cout << ++k;
    return 0;
}


#include <bits/stdc++.h>

#define int long long
#define pii pair<int, int>
#define pb push_back
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, x) for(int i = 0; i < x; i++)
#define rforn(i, x) for(int i = x - 1; i >= 0; i--)
#define printp(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] + 1 << " "; cout << endl;
#define print(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] << " "; cout << endl;

using namespace std;

int n, q;
set<int> dt;
map<int, int> dt_numb;
vector<int> p, ranks, sizes;

void add(int a)
{
    dt.insert(1);
    dt_numb[1]++;
    q++;
    p[a] = a;
    ranks[a] = 1;
    sizes[a] = 1;
}

int find(int a)
{
    if(a < 0 || a >= n || p[a] == -1)
        return -1;
    if(p[a] == a)
        return a;
    return p[a] = find(p[a]);
}

void unite(int a, int b)
{
    a = find(a);
    b = find(b);
    if(a != b && a != -1 && b != -1)
    {
        int s = sizes[a] + sizes[b];
        dt_numb[sizes[a]]--;
        dt_numb[sizes[b]]--;
        if(dt_numb[sizes[a]] == 0)
            dt.erase(sizes[a]);
        if(dt_numb[sizes[b]] == 0)
            dt.erase(sizes[b]);
        q--;
        dt.insert(s);
        dt_numb[s]++;
        if(ranks[a] > ranks[b])
            swap(a, b);
        p[a] = b;
        sizes[b] = s;
        if(ranks[a] == ranks[b])
            ranks[b]++;
    }
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    q = 0;
    cin >> n;
    vector<pii> vec(n);
    forn(i, n)
    {
        cin >> vec[i].ff;
        vec[i].ss = i;
    }

    sort(all(vec));
    p.assign(n, -1);
    ranks.assign(n, 0);
    sizes.assign(n, 0);

    int _max = 0, k = 0;

    forn(i, n)
    {
        int id = vec[i].ss;
        add(id);
        unite(id, id - 1);
        unite(id, id + 1);
        if(dt.size() == 1)
        {
            if(q > _max)
            {
                k = vec[i].ff;
                _max = q;
            }
        }
    }

    cout << ++k;
    return 0;
}


#include <bits/stdc++.h>

#define int long long
#define pii pair<int, int>
#define pb push_back
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, x) for(int i = 0; i < x; i++)
#define rforn(i, x) for(int i = x - 1; i >= 0; i--)
#define printp(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] + 1 << " "; cout << endl;
#define print(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] << " "; cout << endl;

using namespace std;

int n, q;
set<int> dt;
map<int, int> dt_numb;
vector<int> p, ranks, sizes;

void add(int a)
{
    dt.insert(1);
    dt_numb[1]++;
    q++;
    p[a] = a;
    ranks[a] = 1;
    sizes[a] = 1;
}

int find(int a)
{
    if(a < 0 || a >= n || p[a] == -1)
        return -1;
    if(p[a] == a)
        return a;
    return p[a] = find(p[a]);
}

void unite(int a, int b)
{
    a = find(a);
    b = find(b);
    if(a != b && a != -1 && b != -1)
    {
        int s = sizes[a] + sizes[b];
        dt_numb[sizes[a]]--;
        dt_numb[sizes[b]]--;
        if(dt_numb[sizes[a]] == 0)
            dt.erase(sizes[a]);
        if(dt_numb[sizes[b]] == 0)
            dt.erase(sizes[b]);
        q--;
        dt.insert(s);
        if(ranks[a] > ranks[b])
            swap(a, b);
        p[a] = b;
        sizes[b] = s;
        if(ranks[a] == ranks[b])
            ranks[b]++;
    }
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    q = 0;
    cin >> n;
    vector<pii> vec(n);
    forn(i, n)
    {
        cin >> vec[i].ff;
        vec[i].ss = i;
    }

    sort(all(vec));
    p.assign(n, -1);
    ranks.assign(n, 0);
    sizes.assign(n, 0);

    int _max = 0, k = 0;

    forn(i, n)
    {
        int id = vec[i].ss;
        add(id);
        unite(id, id - 1);
        unite(id, id + 1);
        if(dt.size() == 1)
        {
            if(q > _max)
            {
                k = vec[i].ff;
                _max = q;
            }
        }
    }

    cout << ++k;
    return 0;
}


#include <bits/stdc++.h>

#define int long long
#define pii pair<int, int>
#define pb push_back
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, x) for(int i = 0; i < x; i++)
#define rforn(i, x) for(int i = x - 1; i >= 0; i--)
#define printp(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] + 1 << " "; cout << endl;
#define print(x) for(int i = 0; i < (x).size(); i++) cout << (x)[i] << " "; cout << endl;

using namespace std;

int n, q;
set<int> data;
vector<int> p, ranks, sizes;

void add(int a)
{
    data.insert(1);
    q++;
    p[a] = a;
    ranks[a] = 1;
    sizes[a] = 1;
}

int find(int a)
{
    if(a < 0 || a >= n || p[a] == -1)
        return -1;
    if(p[a] == a)
        return a;
    return p[a] = find(p[a]);
}

void unite(int a, int b)
{
    a = find(a);
    b = find(b);
    if(a != b && a != -1 && b != -1)
    {
        int s = sizes[a] + sizes[b];
        data.erase(sizes[a]);
        data.erase(sizes[b]);
        q--;
        data.insert(s);
        if(ranks[a] > ranks[b])
            swap(a, b);
        p[a] = b;
        sizes[b] = s;
        if(ranks[a] == ranks[b])
            ranks[b]++;
    }
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    q = 0;
    cin >> n;
    vector<pii> vec(n);
    forn(i, n)
    {
        cin >> vec[i].ff;
        vec[i].ss = i;
    }

    sort(all(vec));
    p.assign(n, -1);
    ranks.assign(n, 0);
    sizes.assign(n, 0);

    int _max = 0, k = 0;

    forn(i, n)
    {
        int id = vec[i].ss;
        add(id);
        unite(id, id - 1);
        unite(id, id + 1);
        if(data.size() == 1)
        {
            if(q > _max)
            {
                k = vec[i].ff;
                _max = q;
            }
        }
    }

    cout << ++k;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int n;

struct in
{
    int maxn,id;
    bool operator < (const in &aa)const
    {
        return maxn<aa.maxn;
    }
}b[100005];
in c[500005];
int a[100005];

bool cmp(const in &aa,const in &bb)
{
    return aa.maxn<bb.maxn;
}

//---------------------------------

void build(int l,int r,int id)
{
    if(l==r)
    {
        c[id].maxn=a[l];
        c[id].id=l;
        return ;
    }
    int mid=(l+r)/2;
    build(l,mid,id*2);
    build(mid+1,r,id*2+1);
    c[id]=max(c[id*2],c[id*2+1]);
}

in cck(int l,int r,int z,int y,int id)//区间最大值
{
    if(l==z&&r==y)
        return c[id];
    int mid=(l+r)/2;
    if(mid>=y)return cck(l,mid,z,y,id*2);
    else if(mid<z)return cck(mid+1,r,z,y,id*2+1);
    else return max(cck(l,mid,z,mid,id*2),cck(mid+1,r,mid+1,y,id*2+1));
}

//-------------------------------------

int l[100006];//左儿子
int r[100006];//右儿子
int t[100005];//子树个数
int v[100005];//子树点数

int now;//现在这些独立的树中最大的点数
int u;//点数等于现在独立的树中最大点数的树的个数
int tree;//现在独立的树的个数
int an;//最大的相等分段数
int ans;//答案

int dfs(int x,int z,int y)//建树
{
    if(l>r)return 0;
    int nx=cck(1,n,z,y,1).id;
    v[nx]++;
    if(nx<x)
        l[x]=nx;
    if(nx>x)
        r[x]=nx;
    t[x]++;
    if(nx+1<=y)
        v[nx]+=dfs(nx,nx+1,y);
    if(nx-1>=z)
        v[nx]+=dfs(nx,z,nx-1);
    return v[nx];
}

void run()
{
    build(1,n,1);
    int first=cck(1,n,1,n,1).id;
    if(first+1<=n)
        v[first]+=dfs(first,first+1,n);
    if(first-1>=1)
        v[first]+=dfs(first,1,first-1);
    v[first]++;
    an=1;
    ans=b[1].maxn;

    for(int i=1;i<=n;i++)//从小到大加点
    {
        int x=b[i].id;
        tree-=(t[x]-1);

        if(v[x]==now)
            u++;
        if(v[x]>now)
        {
            u=1;
            now=v[x];
        }
        if(u==tree&&u>an)//当所有独立的树都是同样长时，更新答案
        {
            an=u;
            ans=b[i].maxn;
        }
    }

}

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        b[i].maxn=a[i];
        b[i].id=i;
    }
    sort(b+1,b+1+n,cmp);
    run();
    printf("%d\n",ans+1);
    return 0;
}


#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN = 1001010;
struct node{
    int posi, val;
    bool operator < (const node xx)const {
        return val < xx.val;
    }
}a[MAXN];
int p[MAXN];
int find(int x){ return p[x] == x ? x : (p[x] = find(p[x]));}
int ans, n, rec;
int siz[MAXN];
int rem[MAXN], maxv = 1;
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &a[i].val);
        a[i].posi = i;
    }
    sort(a+1, a+1+n);
    for(int i = 1; i <= n; i ++){
        p[a[i].posi] = a[i].posi;
        bool tem = false;
        siz[a[i].posi] = 1;
        rem[1] ++;
        if(p[a[i].posi + 1]){
            tem = true;
            int father = a[i].posi;
            rem[siz[a[i].posi+1]+1] ++;
            rem[siz[a[i].posi+1]] --;
            siz[a[i].posi] = siz[a[i].posi+1]+1;
            rem[1] --;
            p[a[i].posi+1] = a[i].posi;
            maxv = max(siz[father], maxv);
        }
        if(p[a[i].posi-1]){
            tem = true;
            int father = find(a[i].posi - 1);
            rem[siz[father] + siz[a[i].posi]] ++;
            rem[siz[father]] --;
            siz[father] += siz[a[i].posi];
            rem[siz[a[i].posi]] --;
            p[a[i].posi] = father;
            maxv = max(siz[father], maxv);
        }
        if(a[i].val == a[i+1].val)
            continue;
        if(maxv * rem[maxv] == i){
            if(rem[maxv] > rec){
                rec = rem[maxv];
                ans = a[i].val + 1;
            }
        }
    }
    printf("%d", ans);
}


#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN = 1001010;
struct node{
    int posi, val;
    bool operator < (const node xx)const {
        return val < xx.val;
    }
}a[MAXN];
int p[MAXN];
int find(int x){ return p[x] == x ? x : (p[x] = find(p[x]));}
int cnt, ans, n, rec;
int siz[MAXN], siz_now;
int rem[MAXN], maxv = 1;
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &a[i].val);
        a[i].posi = i;
    }
    sort(a+1, a+1+n);
    for(int i = 1; i <= n; i ++){
        p[a[i].posi] = a[i].posi;
        bool tem = false;
        siz[a[i].posi] = 1;
        rem[1] ++;
        if(p[a[i].posi + 1]){
            tem = true;
            rem[siz[a[i].posi+1]+1] ++;
            rem[siz[a[i].posi+1]] --;
            rem[1] --;
            p[a[i].posi+1] = a[i].posi;
            maxv = max(siz[a[i].posi+1]+1, maxv);
        }
        if(p[a[i].posi-1]){
            tem = true;
            int father = find(a[i].posi - 1);
            rem[siz[father] + siz[a[i].posi]] ++;
            rem[siz[father]] --;
            rem[siz[a[i].posi]] --;
            maxv = max(siz[father] + siz[a[i].posi], maxv);
        }
        if(a[i].val == a[i+1].val)
            continue;
        if(maxv * rem[maxv] == i){
            if(rem[maxv] > rec){
                rec = rem[maxv];
                ans = a[i].val + 1;
            }
        }
    }
    printf("%d", ans);
}


#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN = 1001010;
struct node{
    int val, p;
    bool operator < (const node xx) const {
        return val < xx.val;
    }
}a[MAXN];
int n, vis[MAXN], ans = 1, prin, rec = 1;
void check(int x){
    if(vis[x-1] && vis[x+1]){
        rec --;
    }
    else if(vis[x-1] || vis[x+1]){

    }
    else{
        rec ++;
    }
    vis[x] = 1;
}
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &a[i].val);
        a[i].p = i;
    }
    sort(a+1, a+1+n);
    vis[0] = vis[n+1] = 1;
    prin = a[n].val + 1;
    for(int i = n; i > 0; i --){
        vis[a[i].p] = 1;
        check(a[i].p);
        while(a[i].val == a[i-1].val){
            i --;
            vis[a[i].p] = 1;
            check(a[i].p);
        }
        if(ans < rec){
            prin = a[i].val;
            ans = rec;
        }
    }
    printf("%d", prin);
}


#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN = 1001010;
struct node{
    int posi, val;
    bool operator < (const node xx)const {
        return val < xx.val;
    }
}a[MAXN];
int p[MAXN];
int find(int x){ return p[x] == x ? x : (p[x] = find(p[x]));}
int ans, n, rec;
int siz[MAXN];
int rem[MAXN], maxv = 1;
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &a[i].val);
        a[i].posi = i;
    }
    sort(a+1, a+1+n);
    for(int i = 1; i <= n; i ++){
        p[a[i].posi] = a[i].posi;
        bool tem = false;
        siz[a[i].posi] = 1;
        rem[1] ++;
        if(p[a[i].posi + 1]){
            tem = true;
            rem[siz[a[i].posi+1]+1] ++;
            rem[siz[a[i].posi+1]] --;
            rem[1] --;
            p[a[i].posi+1] = a[i].posi;
            maxv = max(siz[a[i].posi+1]+1, maxv);
        }
        if(p[a[i].posi-1]){
            tem = true;
            int father = find(a[i].posi - 1);
            rem[siz[father] + siz[a[i].posi]] ++;
            rem[siz[father]] --;
            rem[siz[a[i].posi]] --;
            p[a[i].posi] = father;
            maxv = max(siz[father] + siz[a[i].posi], maxv);
        }
        if(a[i].val == a[i+1].val)
            continue;
        if(maxv * rem[maxv] == i){
            if(rem[maxv] > rec){
                rec = rem[maxv];
                ans = a[i].val + 1;
            }
        }
    }
    printf("%d", ans);
}


#include<cstdio>
#include<vector>
using namespace std;
const int MAXN = 1001010;
struct node{
    int val, p;
    bool operator < (const node xx) const {
        return val < xx.val;
    }
}a[MAXN];
int n, vis[MAXN], ans = 1, prin, rec = 1;
void check(int x){
    if(vis[x-1] && vis[x+1]){
        rec --;
    }
    else if(vis[x-1] || vis[x+1]){

    }
    else{
        rec ++;
    }
    vis[x];
}
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &a[i].val);
        a[i].p = i;
    }
    sort(a+1, a+1+n);
    vis[0] = vis[n+1] = 1;
    prin = a[n].val + 1;
    for(int i = n; i > 0; i --){
        vis[a[i].p] = 1;
        check(a[i].p);
        while(a[i].val == a[i-1].val){
            i --;
            vis[a[i].p] = 1;
            check(a[i].p);
        }
        if(ans < rec){
            prin = a[i].val;
            ans = rec;
        }
    }
    printf("%d", prin);
}


#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN = 1001010;
struct node{
    int val, p;
    bool operator < (const node xx) const {
        return val < xx.val;
    }
}a[MAXN];
int n, vis[MAXN], ans = 1, prin, rec = 1;
void check(int x){
    if(vis[x-1] && vis[x+1]){
        rec --;
    }
    else if(vis[x-1] || vis[x+1]){

    }
    else{
        rec ++;
    }
    vis[x] = 1;
}
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &a[i].val);
        a[i].p = i;
    }
    sort(a+1, a+1+n);
    vis[0] = vis[n+1] = 1;
    prin = a[n].val + 1;
    for(int i = n; i > 0; i --){
        vis[a[i].p] = 1;
        check(a[i].p);
        while(a[i].val == a[i-1].val){
            i --;
            vis[a[i].p] = 1;
            check(a[i].p);
        }
        if(ans <= rec){
            prin = a[i].val;
            ans = rec;
        }
    }
    printf("%d", prin);
}


#include <bits/stdc++.h>
using namespace std;
#define endl '\n'

signed main()
{
     ios::sync_with_stdio(false);
     cin.tie();
     cout.tie();;
     int n;
     cin >> n;
     vector<pair<int, int>> a(n);
     for (int i = 0; i < n; ++i) {
          cin >> a[i].first;
          a[i].second=i;
     }
     sort(a.begin(), a.end());
     set<pair<int, int>> ss;
     map<int, int> lens;
     set<int> alllens;
     int anscnt = 0;
     int ansnum = 0;
     if (n > 1) {
          anscnt = 1;
          ansnum = a[1].first;
     }
     for (int i = 0; i < n; ++i) {
          pair<int, int> newotr = {a[i].second, a[i].second + 1};
          ss.insert(newotr);
          lens[1]++;
          alllens.insert(1);
          if (ss.size() && i != n - 1) {
               auto it = ss.lower_bound({a[i].second, 0});
               if (it != ss.begin()) {
                    it--;
                    if (it->second == newotr.first) {
                         ss.erase(newotr);
                         lens[1]--;
                         if (lens[1] == 0) {
                              alllens.erase(1);
                         }
                         ss.insert({it->first, newotr.second});
                         lens[it->second - it->first]--;
                         if (lens[it->second - it->first] == 0) {
                              alllens.erase(it->second - it->first);
                         }
                         lens[newotr.second - it->first]++;
                         alllens.insert(newotr.second - it->first);

                         ss.erase(it);
                    }
               }
          }
          if (alllens.size() == 1) {
               if (anscnt < (int)ss.size() - 1) {
                    anscnt = (int)ss.size() - 1;
                    ansnum = a[i + 1].first;
               }
          }
     }
     cout << ansnum;
     return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define endl '\n'

signed main()
{
     ios::sync_with_stdio(false);
     cin.tie();
     cout.tie();;
     int n;
     cin >> n;
     vector<pair<int, int>> a(n);
     for (int i = 0; i < n; ++i) {
          cin >> a[i].first;
          a[i].second=i;
     }
     sort(a.begin(), a.end());
     set<pair<int, int>> ss;
     map<int, int> lens;
     set<int> alllens;
     int anscnt = 0;
     int ansnum = 0;
     if (n > 1) {
          anscnt = 1;
          ansnum = a[1].first;
     }
     for (int i = 0; i < n; ++i) {
          pair<int, int> newotr = {a[i].second, a[i].second + 1};
          ss.insert(newotr);
          lens[1]++;
          alllens.insert(1);
          if (ss.size() && i != n - 1) {
               auto it = ss.lower_bound({a[i].second, 0});
               if (it != ss.begin()) {
                    it--;
                    if (it->second == newotr.first) {
                         ss.erase(newotr);
                         lens[1]--;
                         if (lens[1] == 0) {
                              alllens.erase(1);
                         }
                         ss.insert({it->first, newotr.second});
                         lens[it->second - it->first]--;
                         if (lens[it->second - it->first] == 0) {
                              alllens.erase(it->second - it->first);
                         }
                         lens[newotr.second - it->first]++;
                         alllens.insert(newotr.second - it->first);
                         if (alllens.size() == 1) {
                              if (anscnt < (int)ss.size() - 1) {
                                   anscnt = (int)ss.size() - 1;
                                   ansnum = a[i + 1].first;
                              }
                         }
                         ss.erase(it);
                    }
               }
          }
     }
     cout << ansnum;
     return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define N 110000

int a[N], to[N], ss[N], sum[N], fa[N];
int all, ansx, ansk, n;

bool cmp(int x, int y) {
     return a[x] < a[y];
}

int gf(int x) {
     if (fa[x] != x)
          return gf(fa[x]);
     return fa[x];
}

void merge(int x, int y) {
     x = gf(x);
     y = gf(y);
     if (!y)
          return ;
     ss[sum[x]] -= 1;
     ss[sum[y]] -= 1;
     sum[x] += sum[y];
     fa[y] = x;
     ss[sum[x]] += 1;
}

int main() {
     scanf("%d", &n);
     for (int i = 1; i <= n; i++)
          scanf("%d", &a[i]);
     for (int i = 1; i <= n; i++)
          to[i] = i;
     sort(to + 1, to + n + 1, cmp);
     ansx = 0;
     ansk = 0;
     for (int i = 1; i <= n; i++) {
          sum[to[i]] = 1;
          all += 1;
          ss[1] += 1;
          fa[to[i]] = to[i];
          merge(to[i], to[i] - 1);
          merge(to[i], to[i] + 1);
          if ((i == n || a[to[i] + 1] != a[to[i]]) && all == ss[sum[gf(to[i])]] * sum[gf(to[i])]) {
               int x = ss[sum[gf(to[i])]], k = a[to[i]] + 1;
               if (x > ansx)
                    ansx = x, ansk = k;
          }
     }
     printf("%d\n", ansk);
}


#include <bits/stdc++.h>
using namespace std;
#define endl '\n'

signed main()
{
     ios::sync_with_stdio(false);
     cin.tie();
     cout.tie();;
     int n;
     cin >> n;
     vector<pair<int, int>> a(n);
     for (int i = 0; i < n; ++i) {
          cin >> a[i].first;
          a[i].second=i;
     }
     sort(a.begin(), a.end());
     set<pair<int, int>> ss;
     map<int, int> lens;
     set<int> alllens;
     int anscnt = 0;
     int ansnum = 0;
     if (n > 1) {
          anscnt = 1;
          ansnum = a[1].first;
     }
     for (int i = 0; i < n; ++i) {
          pair<int, int> newotr = {a[i].second, a[i].second + 1};
          ss.insert(newotr);
          lens[1]++;
          alllens.insert(1);
          if (ss.size() && i != n - 1) {
               auto it = ss.lower_bound({a[i].second, 0});
               if (it != ss.begin()) {
                    it--;
                    if (it->second == newotr.first) {
                         ss.erase(newotr);
                         lens[1]--;
                         if (lens[1] == 0) {
                              alllens.erase(1);
                         }
                         ss.insert({it->first, newotr.second});
                         lens[it->second - it->first]--;
                         if (lens[it->second - it->first] == 0) {
                              alllens.erase(it->second - it->first);
                         }
                         lens[newotr.second - it->first]++;
                         alllens.insert(newotr.second - it->first);

                         ss.erase(it);
                    }
               }
          }
          if (alllens.size() == 1) {
               if (anscnt < (int)ss.size()) {
                    anscnt = (int)ss.size();
                    ansnum = a[i + 1].first;
               }
          }
     }
     cout << ansnum;
     return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define fio				std::ios_base::sync_with_stdio(false); cin.tie(NULL)
#define ff 				first
#define ss 				second
#define all(a) 			a.begin(), a.end()
#define pb 				push_back
#define eb 				emblace_back
#define mp 				make_pair
#define ini(n) 			scanf("%d",&n)
#define inl(n) 			scanf("%lld",&n)
#define ins(n) 	    	scanf("%s",n)
#define outi(n) 		printf("%d",n)
#define outl(n) 		printf("%lld",n)
#define outs(n)     	printf("%s",n)
#define fog(x,y,z)		for(x=y;x<z;x++)
#define fol(x,y,z)		for(x=y;x>=z;x--)
#define newl			cout<<endl
typedef long long ll ;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<double> vd;
typedef vector<string> vs;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const ll mod = 1e9+7;
const ll N = 1e2+10;
const ll MAX = 1e18;
template <typename T>T gcd(T x,T y){return y==0?x:gcd(y,x%y);}
template <typename T>T lcm(const T &a,const T &b){return (a*b)/gcd(a,b);}
template <typename T>void pfact(vector<pair<T,T> > &v , T k)
{
	T i ;
	for (i = 2; i <= sqrt(k);i++)
	if (k%i == 0)
	{
		T x = 0;
		while (k%i == 0){k /= i;x++;}
		v.pb(mp(i,x));
	}
	if (k != 1){v.pb(mp(k,1));}
}//vector<pair<ll,ll> > v ;pfact<ll>(v,k);

void sieve(int *spf)
{
    spf[1] = 1;
    for (int i=2; i<N; i++)spf[i] = i;
    for (int i=4; i<N; i+=2)spf[i] = 2;
    for (int i=3; i*i<N; i++){if (spf[i] == i) {for (int j=i*i; j<N; j+=i)if (spf[j]==j) spf[j] = i;}}
}//ll spf[N];sieve(spf);

vector<int> getFactorization(int x,int*spf)
{
    vector<int> ret;
    while (x != 1){ret.push_back(spf[x]);x = x / spf[x];}
    return ret;
}//vector <int> p = getFactorization(x,spf);
#define di  ff.ff
#define sl ff.ss
#define ap  ss.ff
#define bp ss.ss
int main()
{
	//int t;ini(t);while(t--){
	ll i , j , n,s;
	cin>>n>>s;
	ll a[n][4];
	ll ac =0, bc =0, hap=0;
	vector<pair<pair<ll,ll>,pair<ll,ll> > > v(n) ;
	fog(i,0,n)
	{
		cin>>a[i][1]>>a[i][2]>>a[i][3];
		a[i][0]=a[i][2]-a[i][3];
		// if(a[i][1]>=s)
		// {
		// 	a[i][1]-=s;
		// 	hap+=s*max(a[i][2],a[i][3]);
		// }
		v[i].di=a[i][0];
		v[i].sl=a[i][1];
		v[i].ap=a[i][2];
		v[i].bp=a[i][3];
	}
	sort(v.begin(),v.end());
	fog(i,0,n)
	{
		if(v[i].di<0)
		{
			bc+=v[i].sl;
		}
		else
		{
			ac+=v[i].sl;
		}
	}
	if(s==6)
	ll nb =bc - (bc/s)*s;
	ll na = ac -(ac/s)*s;
	if(nb+na>s)
	{
		fog(i,0,n)
		{
			hap+=v[i].sl*max(v[i].ap,v[i].bp);
		}
	}
	else
	{
		fog(i,0,n)
		{
			if(bc>nb && v[i].di<0)
			{
				if(v[i].sl>bc-nb)
				{
					hap+=(bc-nb)*(max(v[i].ap,v[i].bp));
					v[i].sl-=bc-nb;
					bc=nb;

				}
				else
				{
					hap+=v[i].sl*max(v[i].ap,v[i].bp);
					bc-=v[i].sl;
					v[i].sl=0;
				}
			}
			else
			{
				break;
			}
		}

		reverse(v.begin(),v.end());
		fog(i,0,n)
		{
			//cout<<ac<<endl;
			if(ac>na)
			{
				if(v[i].sl>ac-na)
				{
					hap+=(ac-na)*(max(v[i].ap,v[i].bp));
					v[i].sl-=ac-na;
					ac=na;
				}
				else
				{
					hap+=v[i].sl*max(v[i].ap,v[i].bp);
					ac-=v[i].sl;
					v[i].sl=0;
				}
			}
			else
			{
				break;
			}
		}
		ll hap1 = 0 ,hap2=0;
		fog(i,0,n)
		{
			hap1+=v[i].sl*v[i].ap;
			hap2+=v[i].sl*v[i].bp;
		}
	//cout<<hap1<<" "<<hap2<<endl;
		hap+=max(hap1,hap2);
	}
	// if(s==6)
	// {
	// 	fog(i,0,n)
	// 	{
	// 		cout<<v[i].di<<" "<<v[i].sl<<" "<<v[i].ap<<" "<<v[i].bp<<endl;
	// 	}
	// }

	cout<<hap<<endl;
	//cout<<na<<" "<<nb<<endl;
	//}
}


#include <bits/stdc++.h>
using namespace std;
#define fio				std::ios_base::sync_with_stdio(false); cin.tie(NULL)
#define ff 				first
#define ss 				second
#define all(a) 			a.begin(), a.end()
#define pb 				push_back
#define eb 				emblace_back
#define mp 				make_pair
#define ini(n) 			scanf("%d",&n)
#define inl(n) 			scanf("%lld",&n)
#define ins(n) 	    	scanf("%s",n)
#define outi(n) 		printf("%d",n)
#define outl(n) 		printf("%lld",n)
#define outs(n)     	printf("%s",n)
#define fog(x,y,z)		for(x=y;x<z;x++)
#define fol(x,y,z)		for(x=y;x>=z;x--)
#define newl			cout<<endl
typedef long long ll ;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<double> vd;
typedef vector<string> vs;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const ll mod = 1e9+7;
const ll N = 1e2+10;
const ll MAX = 1e18;
template <typename T>T gcd(T x,T y){return y==0?x:gcd(y,x%y);}
template <typename T>T lcm(const T &a,const T &b){return (a*b)/gcd(a,b);}
template <typename T>void pfact(vector<pair<T,T> > &v , T k)
{
	T i ;
	for (i = 2; i <= sqrt(k);i++)
	if (k%i == 0)
	{
		T x = 0;
		while (k%i == 0){k /= i;x++;}
		v.pb(mp(i,x));
	}
	if (k != 1){v.pb(mp(k,1));}
}//vector<pair<ll,ll> > v ;pfact<ll>(v,k);

void sieve(int *spf)
{
    spf[1] = 1;
    for (int i=2; i<N; i++)spf[i] = i;
    for (int i=4; i<N; i+=2)spf[i] = 2;
    for (int i=3; i*i<N; i++){if (spf[i] == i) {for (int j=i*i; j<N; j+=i)if (spf[j]==j) spf[j] = i;}}
}//ll spf[N];sieve(spf);

vector<int> getFactorization(int x,int*spf)
{
    vector<int> ret;
    while (x != 1){ret.push_back(spf[x]);x = x / spf[x];}
    return ret;
}//vector <int> p = getFactorization(x,spf);
#define di  ff.ff
#define sl ff.ss
#define ap  ss.ff
#define bp ss.ss
int main()
{
	//int t;ini(t);while(t--){
	ll i , j , n,s;
	cin>>n>>s;
	ll a[n][4];
	ll ac =0, bc =0, hap=0;
	vector<pair<pair<ll,ll>,pair<ll,ll> > > v(n) ;
	fog(i,0,n)
	{
		cin>>a[i][1]>>a[i][2]>>a[i][3];
		a[i][0]=a[i][2]-a[i][3];
		// if(a[i][1]>=s)
		// {
		// 	a[i][1]-=s;
		// 	hap+=s*max(a[i][2],a[i][3]);
		// }
		v[i].di=a[i][0];
		v[i].sl=a[i][1];
		v[i].ap=a[i][2];
		v[i].bp=a[i][3];
	}
	sort(v.begin(),v.end());
	fog(i,0,n)
	{
		if(v[i].di<0)
		{
			bc+=v[i].sl;
		}
		else
		{
			ac+=v[i].sl;
		}
	}
	if(s==6)
	cout<<ac<<" "<<bc<<endl;
	ll nb =bc - (bc/s)*s;
	ll na = ac -(ac/s)*s;
	if(nb+na>s)
	{
		fog(i,0,n)
		{
			hap+=v[i].sl*max(v[i].ap,v[i].bp);
		}
	}
	else
	{
		fog(i,0,n)
		{
			if(bc>nb && v[i].di<0)
			{
				if(v[i].sl>bc-nb)
				{
					hap+=(bc-nb)*(max(v[i].ap,v[i].bp));
					v[i].sl-=bc-nb;
					bc=nb;

				}
				else
				{
					hap+=v[i].sl*max(v[i].ap,v[i].bp);
					bc-=v[i].sl;
					v[i].sl=0;
				}
			}
			else
			{
				break;
			}
		}
		if(s==6)
		{
			cout<<hap<<endl;
		}
		reverse(v.begin(),v.end());
		fog(i,0,n)
		{
			//cout<<ac<<endl;
			if(ac>na)
			{
				if(v[i].sl>ac-na)
				{
					hap+=(ac-na)*(max(v[i].ap,v[i].bp));
					v[i].sl-=ac-na;
					ac=na;
				}
				else
				{
					hap+=v[i].sl*max(v[i].ap,v[i].bp);
					ac-=v[i].sl;
					v[i].sl=0;
				}
			}
			else
			{
				break;
			}
		}
		if(s==6)
		{
			cout<<hap<<endl;
		}
	}
	// if(s==6)
	// {
	// 	fog(i,0,n)
	// 	{
	// 		cout<<v[i].di<<" "<<v[i].sl<<" "<<v[i].ap<<" "<<v[i].bp<<endl;
	// 	}
	// }

	ll hap1 = 0 ,hap2=0;
	fog(i,0,n)
	{
		hap1+=v[i].sl*v[i].ap;
		hap2+=v[i].sl*v[i].bp;
	}
	//cout<<hap1<<" "<<hap2<<endl;
	hap+=max(hap1,hap2);
	cout<<hap<<endl;
	//cout<<na<<" "<<nb<<endl;
	//}
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<ll> vl;
typedef queue<int> qi;
typedef queue<ll> ql;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define pq priority_queue
#define rep(i,n) for (int i=0;i<n;i++)
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define INF 2000000009
int n,s;
ll ans=0,cur=0,cnt=0;
vector<pll > t1;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>s;
    rep(i,n){
    	ll x,a,b;
    	cin>>x>>a>>b;
    	cur+=(x/s*s)*max(a,b);
    	x%=s;
    	t1.push_back(mp(b-a,x));
    	cur+=x*a;
    	cnt+=x;
    }
    cnt=s-cnt%s;
    ans=max(ans,cur);
    sort(t1.begin(),t1.end());
    reverse(t1.begin(),t1.end());
    int i1=0;
    while(i1<n){
    	int now1=s-cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
			now1=0;
    	}
    	ans=max(ans,cur);
    	now1=cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
    		//t2.push(mp(now1,t1[i1].second));
			now1=0;
    	}
    	ans=max(ans,cur);
    }
    ans=max(ans,cur);
    cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<ll> vl;
typedef queue<int> qi;
typedef queue<ll> ql;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define pq priority_queue
#define rep(i,n) for (int i=0;i<n;i++)
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define INF 2000000009
int n,s;
ll ans=0,cur=0,cnt=0;
vector<pll > t1;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>s;
    rep(i,n){
    	ll x,a,b;
    	cin>>x>>a>>b;
    	if (x/s>0){
    		cur+=((x/s-1)*s)*max(a,b);
    		x%=s;
    		x+=s;
    	}
    	t1.push_back(mp(b-a,x));
    	cur+=x*a;
    	cnt+=x;
    }
    cnt=(s-cnt%s)%s;
    ans=max(ans,cur);
    sort(t1.begin(),t1.end());
    reverse(t1.begin(),t1.end());
    int i1=0;
    while(i1<n){
    	int now1=s-cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
			now1=0;
    	}
    	ans=max(ans,cur);
    	now1=cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    		ans=max(ans,cur);
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
    		ans=max(ans,cur);
    		//t2.push(mp(now1,t1[i1].second));
			now1=0;
    	}
    	ans=max(ans,cur);
    }
    ans=max(ans,cur);
    cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<ll> vl;
typedef queue<int> qi;
typedef queue<ll> ql;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define pq priority_queue
#define rep(i,n) for (int i=0;i<n;i++)
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define INF 2000000009
int n,s;
ll ans=0,cur=0,cnt=0;
vector<pll > t1;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>s;
    rep(i,n){
    	ll x,a,b;
    	cin>>x>>a>>b;
    	cur+=(x/s*s)*max(a,b);
    	x%=s;
    	t1.push_back(mp(b-a,x));
    	cur+=x*a;
    	cnt+=x;
    }
    cnt=s-cnt%s;
    ans=max(ans,cur);
    sort(t1.begin(),t1.end());
    reverse(t1.begin(),t1.end());
    int i1=0;
    while(i1<n){
    	int now1=s-cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
			now1=0;
    	}
    	ans=max(ans,cur);
    	now1=cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    		ans=max(ans,cur);
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
    		ans=max(ans,cur);
    		//t2.push(mp(now1,t1[i1].second));
			now1=0;
    	}
    	ans=max(ans,cur);
    }
    ans=max(ans,cur);
    cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<ll> vl;
typedef queue<int> qi;
typedef queue<ll> ql;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define pq priority_queue
#define rep(i,n) for (int i=0;i<n;i++)
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define INF 2000000009
int n,s;
ll ans=0,cur=0,cnt=0;
vector<pll > t1;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>s;
    rep(i,n){
    	ll x,a,b;
    	cin>>x>>a>>b;
    	t1.push_back(mp(b-a,x));
    	//t2.push_back(mp(b,x));
    	cur+=x*a;
    	cnt+=x;
    }
    cnt=s-cnt%s;
    ans=max(ans,cur);
    sort(t1.begin(),t1.end());
    //sort(t2.begin(),t2.end());
    reverse(t1.begin(),t1.end());
    /*cout<<"~~~~~~~~~~~~~~~~~"<<endl;
    rep(i,n){
    	cout<<t1[i].first<<"  "<<t1[i].second<<endl;
    }
    cout<<"---------"<<endl;
    rep(i,n){
    	cout<<t2[i].first<<"  "<<t2[i].second<<endl;
    }*/
    int i1=0;
    while(i1<n){
    	int now1=s-cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		//t2.push(mp(t1[i1].first.second,t1[i1].second));
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
    		//t2.push(mp(now1,t1[i1].second));
			now1=0;
    	}
    	ans=max(ans,cur);
    	now1=cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		//t2.push(mp(t1[i1].first.second,t1[i1].second));
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
    		//t2.push(mp(now1,t1[i1].second));
			now1=0;
    	}
    	ans=max(ans,cur);
    }
    ans=max(ans,cur);
    cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<ll> vl;
typedef queue<int> qi;
typedef queue<ll> ql;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define pq priority_queue
#define rep(i,n) for (int i=0;i<n;i++)
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define INF 2000000009
int n,s;
ll ans=0,cur=0,cnt=0;
vector<pll > t1;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>s;
    rep(i,n){
    	ll x,a,b;
    	cin>>x>>a>>b;
    	cur+=(x/s*s)*max(a,b);
    	x%=s;
    	t1.push_back(mp(b-a,x));
    	cur+=x*a;
    	cnt+=x;
    }
    cnt=(s-cnt%s)%s;
    ans=max(ans,cur);
    sort(t1.begin(),t1.end());
    reverse(t1.begin(),t1.end());
    int i1=0;
    while(i1<n){
    	int now1=s-cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
			now1=0;
    	}
    	ans=max(ans,cur);
    	now1=cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    		ans=max(ans,cur);
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
    		ans=max(ans,cur);
    		//t2.push(mp(now1,t1[i1].second));
			now1=0;
    	}
    	ans=max(ans,cur);
    }
    ans=max(ans,cur);
    cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<ll> vl;
typedef queue<int> qi;
typedef queue<ll> ql;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define pq priority_queue
#define rep(i,n) for (int i=0;i<n;i++)
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define INF 2000000009
int n,s;
ll ans=0,cur=0,cnt=0;
vector<pll > t1;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>s;
    rep(i,n){
    	ll x,a,b;
    	cin>>x>>a>>b;
    	cur+=((x/s-1)*s)*max(a,b);
    	x%=s;
    	x+=s;
    	t1.push_back(mp(b-a,x));
    	cur+=x*a;
    	cnt+=x;
    }
    cnt=(s-cnt%s)%s;
    ans=max(ans,cur);
    sort(t1.begin(),t1.end());
    reverse(t1.begin(),t1.end());
    int i1=0;
    while(i1<n){
    	int now1=s-cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
			now1=0;
    	}
    	ans=max(ans,cur);
    	now1=cnt;
    	while (t1[i1].second<=now1&&i1<n){
    		now1-=t1[i1].second;
    		cur+=t1[i1].second*t1[i1].first;
    		t1[i1].second=0;
    		i1++;
    		ans=max(ans,cur);
    	}
    	if (i1<n){
    		t1[i1].second-=now1;
    		cur+=now1*t1[i1].first;
    		ans=max(ans,cur);
    		//t2.push(mp(now1,t1[i1].second));
			now1=0;
    	}
    	ans=max(ans,cur);
    }
    ans=max(ans,cur);
    cout<<ans;
}


#include<bits/stdc++.h>

using namespace std;

using ui = uint32_t;

uint64_t compute_happiness(
    const uint64_t S, const uint64_t total_a_pizzas, const uint64_t total_b_pizzas,
    const vector<ui> &as, const vector<ui> &bs, const vector<ui> &ss, const vector<ui> &is
    ) {

    // cerr << "Will try with " << total_a_pizzas << " " << total_b_pizzas << endl;

    uint64_t H = 0;
    uint64_t s = 0;
    uint64_t i = 0;

    uint64_t togo = 0;

    const auto total_a_slices = S * total_a_pizzas;

    for (; i != is.size() && s != total_a_slices; ++i) {
        const auto person = is[i];
        const auto slices = ss[person];

        const auto to_eat = s + slices <= total_a_slices ? slices : total_a_slices - s;

        s += to_eat;
        H += to_eat * as[person];

        togo = slices - to_eat;

        // cerr << "Person " << i << " ate " << to_eat << " (" << togo << " togo)" << ", bumping to (slices, happiness): " << "(" << s << ", " << H << ")" << endl;
    }

    if (i != 0 && i != is.size()) {
        H += togo * bs[is[i - 1]];

        s = togo;

        // cerr << "Account for togo, bumping to (slices, happiness): " << "(" << s << ", " << H << ")" << endl;
    }

    for (; i != is.size(); ++i) {
        const auto person = is[i];
        const auto slices = ss[person];

        H += slices * bs[person];
        // cerr << "Person " << i << " ate " << slices << ", bumping to (slices, happiness): " << "(" << s << ", " << H << ")" << endl;

    }

    // cerr << "=========== final happiess: " << H << endl;

    return H;
}

int main() {

    ui N, S;
    uint64_t H, ats, bts, uts;
    cin >> N >> S;

    H = 0;
    ats = 0;  // total slices of a (first pizza)
    bts = 0;  // total slices of b (second pizza)
    uts = 0;  // total slices of undecided

    auto ss = vector<ui>(N, 0);
    auto as = vector<ui>(N, 0);
    auto bs = vector<ui>(N, 0);
    auto is = vector<ui>(N, 0);

    for (ui i = 0; i != N; ++i) {
        cin >> ss[i];
        cin >> as[i];
        cin >> bs[i];

        is[i] = i;

        if (as[i] == bs[i]) {
            uts += ss[i];
        } else if (as[i] > bs[i]) {
            ats += ss[i];
        } else {
            bts += ss[i];
        }
    }

    sort(
        is.begin()
        , is.end()
        , [&as, &bs] (const auto &lhs, const auto &rhs) {
              // Reorder the elements so that:
              // 1. In the fron you have people who will be very upset if they don't eat pizza of type a
              // 2. At the back you have people who will be very upset if they don't eat pizza of type b
              // 3. In the middle you have people who don't have such a strong difference in happiness for pizza's a or b
              // Somewhere in category 3 people will have to eat "the wrong" single pizza
              if (as[lhs] >= bs[lhs] && as[rhs] >= bs[rhs]) {
                  // Both prefer pizza A, figure out who will be more upset and push to front
                  if (as[lhs] - bs[lhs] >= as[rhs] - bs[rhs]) {
                      return true;
                  } else {
                      return false;
                  }
              } else if (as[lhs] < bs[lhs] && as[rhs] < bs[rhs]) {
                  // Both prefer pizza B, figure out who will be more upset and push to back
                  if (bs[lhs] - as[lhs] <= bs[rhs] - as[rhs]) {
                      return true;
                  } else {
                      return false;
                  }
              } else if (as[lhs] >= bs[lhs] && as[rhs] < bs[rhs]) {
                  // Left prefers A, while right prefers B, push left to front and right to back
                  return true;
              } else if (as[lhs] < bs[lhs] && as[rhs] >= bs[rhs]) {
                  // Right prefers Bm while left prefers A, push left to back and right to front
                  return false;
              }

              // This should never be reached, return false to pelase the compiler
              // throw runtime_error("Comparator is broken");
              return false;
          }
        );

    // cerr << "The order is:" << endl;
    // for (auto i : is) {
    //     cerr << ss[i] << " " << as[i] << " " << bs[i] << endl;
    // } cerr << "==============" << endl;

    uint64_t total_pizzas = (ats + bts + uts + S - 1) / S;
    uint64_t total_a_pizzas = (ats + S - 1) / S;
    uint64_t total_b_pizzas = (bts + S - 1) / S;

    if (total_a_pizzas + total_b_pizzas <= total_pizzas) {
        // everybody eats what they want, optimal happiness
        for (ui i = 0; i != N; ++i) {
            if (as[i] >= bs[i]) {
                H += ((uint64_t) ss[i]) * as[i];
            } else {
                H += ((uint64_t) ss[i]) * bs[i];
            }
        }
    } else {
        // there is one pizza that must be split, suboptimal happiness
        // total_a_pizzas + total_b_pizzas == total_pizzas + 1
        // just bruteforce which pizza type should suffer: first or second?

        auto Ha = compute_happiness(S, total_a_pizzas, total_b_pizzas - 1, as, bs, ss, is);
        auto Hb = compute_happiness(S, total_a_pizzas - 1, total_b_pizzas, as, bs, ss, is);

        if (Ha >= Hb) {
            H = Ha;
        } else {
            H = Hb;
        }
    }

    cout << H << endl;
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <bitset>
#include <map>
#include <vector>
#include <stack>
#include <set>
#include <unordered_set>
#include <cmath>
#ifdef LOCAL
#define debug(x) cout<<#x<<" = "<<(x)<<endl;
#else
#define debug(x) 1;
#endif

#define chmax(x,y) x=max(x,y)
#define chmin(x,y) x=min(x,y)
#define lson id<<1,l,mid
#define rson id<<1|1,mid+1,r
#define lowbit(x) x&-x
#define mp make_pair
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<ll, int> pii;

const int MOD = 1e9 + 7;
const double eps = 1e-10;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fll;
const int MAXN = 1e6 + 5;
const int mod = 1e9 + 7;

struct nodes {
    int s, a, b;
    bool operator < (const nodes & x) const {
        return a - b > x.a - x.b;
    }
} nd[MAXN];
ll totnum;
int n, S;
ll suf[MAXN];

ll calc (ll n) {
    ll ans = 0;
    ll n1 = n * S, n2 = (totnum - n) * S;
    for (int i = 1; i <= ::n; i++) {
        if (nd[i].b >= nd[i].a && suf[i] > n2 && suf[i] - n2 <= nd[i].s) {
            ans += (ll) nd[i].a * (suf[i] - n2);
            ans += (ll) nd[i].b * (nd[i].s - suf[i] + n2);
            n1 -= suf[i] - n2;
            n2 -= (nd[i].s - suf[i] + n2);
        } else if (nd[i].b >= nd[i].a && suf[i] <= n2) {
            n2 -= nd[i].s;
            ans += (ll) nd[i].b * nd[i]. s;
        } else if (n1) {
            if (n1 < nd[i].s) {
                ans += (ll) nd[i].b * (nd[i].s - n1);
                ans += (ll) nd[i].a * n1;
                n2 -= nd[i].s - n1;
                n1 = 0;
            } else {
                ans += (ll) nd[i].a * nd[i].s;
                n1 -= nd[i].s;
            }
        } else {
            ans += (ll) nd[i].b * nd[i].s;
            n2 -= nd[i].s;
        }
    }
    return ans;
}

ll solve (ll l, ll r) {
    while (l < r) {
        ll m1 = floor (1.0 * (2 * l + r) / 3), m2 = floor (1.0 * (l + 2 * r + 2) / 3);
        if (calc (m1) < calc (m2) ) l = m1 + 1;
        else r = m2 - 1;
    }

    ll vl = calc (l), vr = calc (r);
    return max (vl, vr);
}

int main() {
#ifdef LOCAL
    freopen ("input.txt", "r", stdin);
#endif
    scanf ("%d %d", &n, &S);
    ll tot = 0;
    for (int i = 1; i <= n; i++) {
        scanf ("%d %d %d", &nd[i].s, &nd[i].a, &nd[i].b);
        tot += nd[i].s;
    }
    sort (nd + 1, nd + 1 + n);
    for (int i = n; i >= 1; i--) suf[i] = nd[i].s + suf[i + 1];
    totnum = (tot + S - 1) / S;
    ll l = 0, r = totnum;
    printf ("%lld\n", solve (l, r)  );
    return 0;
}

// This is just a test to see if it works