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
#include <bits/stdc++.h>
using namespace std;
#define int long long

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    int n;
    cin >> n;
    vector<int> a(n);
    for(int i=0;i<n;i++)
    cin >> a[i];

    int gm = a[0];
    int last = 0;
    
    for(int i=1;i<n;i++){
        if(a[i] > gm){
            gm = a[i];
            last = i;
        }
        else if(a[i] == gm)
        last = i;
    }
    
    vector<int> nast(n,-1);
    stack<int> s;
    
    for(int i=2*n-1;i>=0;i--){
        int id = i%n;
        
        while(!s.empty() && a[s.top()] <= a[id])
            s.pop();
            
        if(i<n && !s.empty())
        nast[id] = s.top();
            
        s.push(id);
    }

    vector<int> dp(n);
    int odp = 0;
    int i = last;
    
    do{
        if(nast[i] == -1)
            dp[i] = 1;
        else
            dp[i] = dp[nast[i]] + 1;
            
        if(dp[i] > odp)
            odp = dp[i];
        i= (i-1+n)%n;
    }while(i != last);

    cout << odp;
}