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
#include <bits/stdc++.h>

using namespace std;

int n;
int A[2'000'006];
int jumps[2'000'006][21];


int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    cin >> n;
    for (int i = 0; i < n; ++i) cin >> A[i];
    for (int i = n; i < 2 * n; ++i) A[i] = A[i - n];

    stack<int> s;
    for (int i = 0; i < 2 * n; ++i) {
        while (!s.empty() && A[s.top()] < A[i]) {
            jumps[s.top()][0] = i;
            s.pop();
        }
        s.push(i);
    }
    while (!s.empty()) {
        jumps[s.top()][0] = 2 * n;
        s.pop();
    }

    for (int i = 0; i < 21; ++i) jumps[2 * n][i] = 2 * n;

    for (int j = 1; j < 21; ++j) {
        for (int i = 0; i < 2 * n; ++i) {
            jumps[i][j] = jumps[jumps[i][j - 1]][j - 1];
        }
    }

    int output;
    for (int i = 0; i < n; ++i) {
        int curr = i;
        int score = 1;

        for (int j = 20; j >= 0; --j) {
            if (jumps[curr][j] < i + n) {
                curr = jumps[curr][j];
                score += (1 << j);
            }
        }
        output = max(output, score);
    }

    cout << output;
	return 0;
}