1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>
using namespace std;
int main() {
    cin.tie(0)->sync_with_stdio(0);
    int n;cin>>n;
    int a[n],dp[n],maxsuf[n];
    for (auto&& e : a)cin>>e;
    vector<int> stack;
    for (int i=n-1;i>=0;--i){
        while (!stack.empty()&&stack.back()<=a[i])stack.pop_back();
        stack.push_back(a[i]);
        dp[i]=stack.size();
        maxsuf[i]=stack.front();
    }
    stack.clear();
    int add=0,maxres=*dp,maxadded=0;
    for (int i=1;i<n;++i) {
        if (!maxadded&&(stack.empty()||a[i-1]>stack.back()))
            stack.push_back(a[i-1]);
        else if (maxadded&&a[i-1]>maxadded)++add,maxadded=a[i-1];
        while (!stack.empty()&&stack.back()>maxsuf[i]) {
            if (!maxadded)maxadded=stack.back();
            stack.pop_back();
            ++add;
        }
        if (dp[i]+add>maxres)maxres=dp[i]+add;
    }
    cout << maxres;
}