Problem:
Score : 400 points

Problem Statement

You are given a sequence A_1, A_2, ..., A_N and an integer K.

Print the maximum possible length of a sequence B that satisfies the following conditions:

B is a (not necessarily continuous) subsequence of A.

For each pair of adjacents elements of B, the absolute difference of the elements is at most K.

Constraints

1 \leq N \leq 300,000

0 \leq A_i \leq 300,000

0 \leq K \leq 300,000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1
A_2
:
A_N

Output

Print the answer.

Sample Input 1

10 3
1
5
4
3
8
6
9
7
2
4

Sample Output 1

7

For example, B = (1, 4, 3, 6, 9, 7, 4) satisfies the conditions.

It is a subsequence of A = (1, 5, 4, 3, 8, 6, 9, 7, 2, 4).

All of the absolute differences between two adjacent elements (|1-4|, |4-3|, |3-6|, |6-9|, |9-7|, |7-4|) are at most K = 3.

Solution in C (GCC 9.2.1) (judge verdict: Wrong Answer)

#include<stdio.h>
int left[1500000],right[1500000],tree[1500000],lazy[1500000]={0};
int a[400000],f[400000]={0},record[400000];
int min(int a,int b){
	if (a<b) return a;else return b;
}
int max(int a,int b){
	if (a>b) return a;else return b;
}
void build(int l,int r,int k){
   tree[k]=0;
   left[k]=l;
   right[k]=r;
   lazy[k]=0;
   int mid=(l+r)/2;
   if (l==r) {record[l]=k;return;}
   build(l,mid,k*2);
   build(mid+1,r,k*2+1);	
}
void laze(int k){
   if (k>=4*300000) return;
   lazy[k*2]=max(lazy[k*2],lazy[k]); lazy[k*2+1]=max(lazy[k],lazy[k*2+1]);
   tree[k]=max(tree[k],lazy[k]);
   lazy[k]=0; 
}
int find(int l,int r,int k){
	if (k>4*300000) return 0;
    laze(k);
	if (r<left[k]||l>right[k]) return 0;
	if (left[k]>=l&&right[k]<=r) return tree[k];
	int ans1=find(l,r,k*2);
	int ans2=find(l,r,k*2+1);
	return max(ans1,ans2);
}
void update(int l,int r,int num,int k){
	if (k>4*300000) return;
	laze(k);
	if (r<left[k]||l>right[k]) return;
	if (left[k]>=l&&right[k]<=r) {
		lazy[k]=num;
		laze(k);
		return;
	}
		update(l,r,num,k*2);
		update(l,r,num,k*2+1);
		tree[k]=max(tree[k*2],tree[k*2+1]);
}
int main(){
	int n,k;
	scanf("%d %d",&n,&k);
	for (int i=1;i<=n;i++)
	   scanf("%d",&a[i]);
	build(0,300000,1);
	for (int i=1;i<=n;i++){
		f[i]=find(a[i],a[i],1)+1;
		update(max(0,a[i]-k),min(a[i]+k,300000),f[i],1);
	}
	int ans=0;
	for (int i=1;i<=n;i++){
		if (f[i]>ans)
		 ans=f[i];
	}
	printf("%d",ans);
}