Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Chamo and Mocha's Array

#include <bits/stdc++.h>
using namespace std;

const int inf = 1e6;

int solve(vector<int> &a) {
    int n = a.size();
    map<int, vector<int>> pos;
    for (int i = 0; i < n; i++) {
        pos[a[i]].push_back(i);
    }

    set<int, greater<int>> original(a.begin(), a.end());
    set<int> have;

    int min_diff = inf;
    for (auto &ele : original) {
        for (auto &idx : pos[ele]) {
            auto rhs = have.lower_bound(idx);
            if (rhs != have.end()) {
                min_diff = min(min_diff, *rhs - idx);
            }
            if (rhs != have.begin()) {
                rhs--;
                min_diff = min(min_diff, idx - *rhs);
            }
            have.insert(idx);
        }
        if (min_diff <= 2) {
            return ele;
        }
    }

    return a.back();
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        int n;
        cin >> n;
        vector<int> a(n);
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        cout << solve(a) << "\n";
    }
    return 0;
}