#include "towers.h"
#include <bits/stdc++.h>
#define ent '\n'
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 12;
int dp[maxn], a[maxn];
int p[20][maxn], lg[maxn];
int n, d;
struct segtree{
int t[maxn * 4];
segtree(){
for(int i=0;i<maxn*4;i++){
t[i] = 0;
}
}
void upd(int v, int tl, int tr, int pos, int x){
if(tl == tr){
t[v] = x;
}
else{
int mid = tl + tr >> 1;
if(pos <= mid){
upd(v*2, tl, mid, pos, x);
}
else{
upd(v*2+1, mid+1, tr, pos, x);
}
t[v] = max(t[v*2], t[v*2+1]);
}
}
int get(int v, int tl, int tr, int l, int r){
if(tl > r || l > tr) return 0;
if(tl >= l && tr <= r) return t[v];
int mid = tl + tr >> 1;
return max(get(v*2, tl, mid, l, r), get(v*2+1, mid+1, tr, l, r));
}
} ft, st;
int get(int l, int r){
if(l > r) return 0;
int k = lg[r - l + 1];
return max(p[k][l], p[k][r - (1 << k) + 1]);
}
void init(int N, std::vector<int> H) {
n = N;
for(int i=1;i<=n;i++){
a[i] = p[0][i] = H[i - 1];
if(i > 1) lg[i] = lg[i / 2] + 1;
}
for(int k=1;k<20;k++){
for(int i=1;i + (1 << k) - 1 <= n;i++){
p[k][i] = max(p[k-1][i], p[k-1][i + (1 << (k - 1))]);
}
}
}
int max_towers(int l, int r, int D) {
d = D;
l++, r++;
vector<int> ord;
for(int i=l;i<=r;i++){
ord.push_back(i);
}
sort(ord.begin(), ord.end(), [](int i, int j){
return a[i] < a[j];
});
set<int> s;
for(int i:ord){
auto it = s.upper_bound(i);
bool ok = 1;
ok &= (it == s.end() || get(i + 1, *it - 1) - d >= a[i]);
if(s.size() && it != s.begin()){
it--;
ok &= (get(*it+1, i-1) - d >= a[i]);
}
if(ok) s.insert(i);
}
return s.size();
}