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 Rust (1.42.0) (judge verdict: Accepted)

fn main() {
	let mut s = String::new();
	use std::io::Read;
	std::io::stdin().read_to_string(&mut s).unwrap();
	let mut s = s.split_whitespace();
	let n: usize = s.next().unwrap().parse().unwrap();
	let k: i32 = s.next().unwrap().parse().unwrap();
	let mut st = SegmentTree::new(300001, 0, |a, b| std::cmp::max(a, b));
	for _ in 0..n {
		let a: i32 = s.next().unwrap().parse().unwrap();
		let l = std::cmp::max(0, a - k);
		let r = std::cmp::min(300000, a + k);
		let m = st.fold(l as usize, r as usize + 1);
		st.set(a as usize, m + 1);
	}
	println!("{}", st.fold(0, 300001));
}

pub struct SegmentTree<T, F> {
	n: usize,
	data: Vec<T>,
	e: T,
	op: F,
}

impl<T, F> SegmentTree<T, F>
where
	T: Clone,
	F: Fn(T, T) -> T,
{
	pub fn new(n: usize, e: T, op: F) -> Self {
		Self {
			n: n,
			data: vec![e.clone(); n << 1],
			e: e,
			op: op,
		}
	}

	pub fn construct(src: Vec<T>, e: T, op: F) -> Self {
		let mut data = vec![e.clone(); src.len()];
		data.extend(src);
		for i in (1..data.len() / 2).rev() {
			data[i] = op(data[i << 1].clone(), data[i << 1 | 1].clone());
		}
		Self {
			n: data.len() / 2,
			data,
			e,
			op,
		}
	}

	pub fn fold(&self, l: usize, r: usize) -> T {
		let mut s = self.e.clone();
		let mut t = self.e.clone();
		let mut l = l + self.n;
		let mut r = r + self.n;
		while l < r {
			if l & 1 != 0 {
				s = (self.op)(s, self.data[l].clone());
				l += 1;
			}
			if r & 1 != 0 {
				t = (self.op)(self.data[r - 1].clone(), t);
			}
			l >>= 1;
			r >>= 1;
		}
		(self.op)(s, t)
	}

	pub fn set(&mut self, i: usize, v: T) {
		let mut i = i + self.n;
		self.data[i] = v;
		while {
			i >>= 1;
			i > 0
		} {
			self.data[i] = (self.op)(self.data[i << 1].clone(), self.data[i << 1 | 1].clone());
		}
	}

	pub fn get(&self, i: usize) -> Option<&T> {
		self.data.get(self.n + i)
	}

	pub fn len(&self) -> usize {
		self.n
	}
}