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

const int base = 1 << 20;
int c[base]; //this string
int dp_max[base]; //maximum value at the end of the string
int dp_lg[base]; //maxim lenght of this pretty string
vector<int> new_c; //string after rotation
vector<int> rm_old_max; //removing old maxes
int counter = 0;


int32_t main(){

    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);
    int n; cin >> n;
    for(int i = 1; i <= n; i++) cin >> c[i];
    for(int i = n; i >= 1; i--){
        while(!rm_old_max.empty() && rm_old_max.back() <= c[i]){ //usuniecie mniejszego goscia z wyniku
            counter--;
            rm_old_max.pop_back();
        }
        rm_old_max.push_back(c[i]);
        counter++;

        dp_max[i] = max(dp_max[i + 1], c[i]);
        dp_lg[i] = counter;
    }

    int best_res = dp_lg[1];
    for(int i = 1; i <= n; i++){
        if(new_c.empty() || new_c.back() < c[i]) new_c.push_back(c[i]);
        int poc = 0, kon = new_c.size() - 1, res = 0;
        while(poc <= kon){
            int mid = (poc + kon)/2;
            if(dp_max[i + 1] >= new_c[mid])
                poc = mid + 1;
            else{
                kon = mid - 1;
                res = new_c.size() - mid;
            }
        }

        best_res = max(best_res, dp_lg[i + 1] + res);
    }

    cout << best_res;
    return 0;
}