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
#include <iostream>
#include <stack>

using namespace std;

const int MAX_N_2 = 2000005;

int n;
int a[MAX_N_2];
int prevElem[MAX_N_2], len[MAX_N_2], res;

stack<pair<int, int>> high; // first - val, second - idx

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

    cin >> n;

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

    for (int i = 2 * n; i > 0; --i)
    {
        while (!high.empty() && high.top().first <= a[i])
        {
            high.pop();
        }

        if (high.empty())
        {
            len[i] = 1;
        }
        else
        {
            len[i] = len[high.top().second] + 1;
        }

        if (len[i] > res)
        {
            res = len[i];
        }

        high.push(make_pair(a[i], i));
    }

    cout << res << endl;
}