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
#include <utility>
#include <algorithm>
#include <deque>
#include <vector>
#include <iostream>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0);
    
    int n; cin >> n;
    int m = n * 2 - 1;
    vector<int> a(m);
    for (int i = 0; i < n; i++) { 
        cin >> a[i];
        if (i < n - 1) a[i + n] = a[i];
    }

    vector<int> nxt(m, m), stack;
    for (int i = m - 1; i >= 0; i--) {
        while (!stack.empty() && a[stack.back()] <= a[i]) stack.pop_back();
        if (!stack.empty()) nxt[i] = stack.back();
        stack.push_back(i);
    }
    // for (int i = 0; i < m; i++) cout << i << ": " << nxt[i] << '\n';

    deque<pair<int,int>> dq;
    int mx = 0, cur = 0;
    for (int i = 0; i < n; i++) {
        if (a[i] > mx) {
            cur++;
        }
        mx = max(mx, a[i]);
        while (!dq.empty() && dq.back().first <= a[i]) dq.pop_back();
        dq.push_back({a[i], i});
    }

    int res = cur;
    for (int l = 0; l < n - 1; l++) {
        // cout << l << ' ' << n + l << " : " << a[l] << ' ' << a[l + n] << " -------\n";
        cur--;
        while (!dq.empty() && dq.front().second <= l) dq.pop_front();

        if (a[l] >= a[l + 1]) {
            int i = l + 1;
            mx = 0;
            while (i < l + n && a[l] >= a[i]) {
                // cout << i << '\n';
                if (a[i] > mx) cur++;
                if (a[i] == a[l]) break;
                mx = max(mx, a[i]);
                i = nxt[i];
            }
        }
        if (a[l + n] > dq.front().first) {
            cur++;
        }
        while (!dq.empty() && dq.back().first <= a[l + n]) dq.pop_back();
        dq.push_back({a[l + n], l + n});
        res = max(res, cur);
        // cout << "cur: " << cur << '\n'; 
    }
    cout << res << '\n';
    return 0;
}
/*

4
2 1 1 2

4
3 2 1 3

7
1 7 2 3 7 2 9

*/