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)

use std::io::Read;
use std::cmp;

struct SegTree {
  data : Vec<usize>,
  offset : usize
}
impl SegTree {
  fn new(n: usize) -> SegTree {
    let offset = n.next_power_of_two();
    let data = vec![0_usize; 2 * offset];
    SegTree{ data, offset }
  }
  fn update(&mut self, x :usize, v: usize) {
    self.data[self.offset + x] = v;
    let mut k = (self.offset + x) / 2;
    while k > 0 {
      self.data[k] = cmp::max(self.data[2 * k], self.data[2 * k + 1]);
      k /= 2;
    }
  }
  fn range_max(&self, a:usize, b:usize) -> usize {
    self.rmax(a, b, 1, 0, self.offset)
  }
  fn rmax(&self, a:usize, b:usize, k:usize, l:usize, r:usize) -> usize {
    if r <= a || b <= l {
      0
    } else if a <= l && r <= b {
      self.data[k]
    } else {
      let mid = (l + r) / 2;
      cmp::max(self.rmax(a,b,2 * k,l,mid), self.rmax(a,b,2 * k + 1, mid, r))
    }
  }
  fn max(&self) -> usize {
    self.data[1]
  }
}

fn main() {
  let mut buf = String::new();
  std::io::stdin().read_to_string(&mut buf).unwrap();
  let A : Vec<usize> = buf.split_whitespace().map(|x|x.parse().unwrap()).collect();
  let N = A[0];
  let K = A[1];
  let mut st = SegTree::new(300_100);
  for &a in &A[2 ..] {
    let s = cmp::max(0, (a as isize) - (K as isize)) as usize;
    let t = cmp::min(300_100, (a as isize) + (K as isize) + 1) as usize;
    let v = st.range_max(s, t);
    st.update(a, v + 1);
  }
  println!("{}", st.max());
}