KPLANK - Bán dừa

Tác giả: flashmt

Ngôn ngữ: C++

#include <iostream>
#include <algorithm>
#include <cstdio>
#define fr(a,b,c) for (a=b;a<=c;a++)
#define N 1000100
using namespace std;
 
int re,n,a[N],m,st[N],pos[N];
 
int main()
{
        int i;
        cin >> n;
        fr(i,1,n) scanf("%d",&a[i]);
        st[0]=-1; m=pos[0]=0; 
        fr(i,1,n)
                if (a[i]>st[m]) 
                {
                        st[++m]=a[i]; pos[m]=i;
                }
                else
                {
                        while (a[i]<=st[m]) 
                        {
                                re=max(re,(st[m]<=i-pos[m]+(a[i]==st[m])?st[m]:0));
                                m--;
                        }
                        st[++m]=a[i];
                }
        fr(i,1,m) re=max(re,(st[i]<=n-pos[i]+1?st[i]:0));
        cout << re << endl;
        return 0;
}

Download