Code : Yet Another Monster Fight
#include <bits/stdc++.h>
using namespace std;
long long solve(vector<long long> &a) {
int n = a.size();
vector<long long> prefix_max_when_source_is_to_the_right(n);
vector<long long> suffix_max_when_source_is_to_the_left(n);
long long current_max = -1;
for (int i = 0; i < n; i++) {
// In the worst case, all elements to the right would be deleted first
// Hence, x - right_count >= a[i]
// x >= a[i] + right_count
long long current_cost = a[i] + (n - 1) - i;
prefix_max_when_source_is_to_the_right[i] =
max(current_cost, current_max);
current_max = max(current_max, current_cost);
}
current_max = -1;
for (int i = n - 1; i >= 0; i--) {
// In the worst case, all elements to the left would be deleted first
// Hence, x - left_count >= a[i]
// x >= a[i] + left_count
long long current_cost = a[i] + i;
suffix_max_when_source_is_to_the_left[i] =
max(current_cost, current_max);
current_max = max(current_max, current_cost);
}
vector<long long> source(n, 0);
// source[i] is the answer when the source is the (i-th) element.
for (int i = 0; i < n; i++) {
source[i] = a[i];
if (i - 1 >= 0) {
source[i] =
max(source[i], prefix_max_when_source_is_to_the_right[i - 1]);
}
if (i + 1 < n) {
source[i] =
max(source[i], suffix_max_when_source_is_to_the_left[i + 1]);
}
}
return *min_element(source.begin(), source.end());
}
int main() {
int n;
cin >> n;
vector<long long> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
auto res = solve(a);
cout << res << endl;
return 0;
}