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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

typedef long long ll;
typedef long double ld;

#define pb push_back
#define pii pair<int, int>
#define pll pair<ll, ll>
#define st first
#define nd second
#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
#define debug false

const int MAXN = 1000 * 1000 + 17;
const int MAXLOG = 21;
int a[MAXN];
int dp[MAXN];
stack<int> s;
int kol[MAXN];
int jp[MAXN][MAXLOG];

int main () {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

    int n;
    cin >> n;

    for (int i = 0; i < n; i ++) {
        cin >> a[i];
        kol[i] = n;
    }

    jp[n][0] = n;
    for (int i = n - 1; i >= 0; i --) {
        while (!s.empty() && a[s.top()] <= a[i]) {
            s.pop();
        }
        if (!s.empty()) {
            jp[i][0] = s.top();
            kol[i] = s.top();
        } else {
            jp[i][0] = n;
        }
        dp[i] = dp[kol[i]] + 1;
        s.push(i);
    }

    for (int i = n - 1; i >= 0; i --) {
        while (!s.empty() && a[s.top()] <= a[i]) {
            s.pop();
        }
        if (kol[i] == n && !s.empty()) {
            kol[i] = s.top();
        }
        s.push(i);
    }

    for (int j = 1; j < MAXLOG; j ++) {
        for (int i = 0; i <= n; i ++) {
            jp[i][j] = jp[jp[i][j - 1]][j - 1];
        }
    }


    int wyn = dp[0];
    int maks = n - 1;
    for (int i = n - 1; i >= 1; i --) {
        if (a[i] > a[maks]) {
            maks = i;
        }

        int x = kol[maks];
        if (x == n) {
            wyn = max(wyn, dp[i]);
        } else {
            int cnt = 1;
            for (int j = MAXLOG - 1; j >= 0; j --) {
                if (jp[x][j] < i) {
                    cnt += (1 << j);
                    x = jp[x][j];
                }
            }
            wyn = max(wyn, dp[i] + cnt);
        }
    }

    cout << wyn << "\n";

    return 0;
}