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)

#![allow(dead_code, unused_imports, deprecated)]
use std::cmp;
use std::collections::*;
use maplit::*;
use num::Integer;
use proconio::input;
use proconio::marker::*;
use proconio::fastout;

const INF : usize = 1000000007;

#[fastout]
fn main() {
  input! {
    n: usize, k: usize,
  };

  let m = 300_000;
  let mut seg = SegmentTree::<usize>::new(m + 1, cmp::max, 0);

  let mut res = 0;
  for _ in 0..n {
    input! {
      a: usize,
    };

    let l = cmp::max(k, a) - k;
    let r = cmp::min(m, a + k);
    let v = seg.query(l, r + 1) + 1;
    res = cmp::max(res, v);
    seg.update(a, v);
  }
  
  println!("{}", res);
}

struct SegmentTree<T: Default = usize>
  where T : {
  node: Vec<T>,
  offset: usize,
  op: fn(T, T) -> T,
  id: T,
}

impl<T> SegmentTree<T>
  where T : std::default::Default
    + std::clone::Clone
    + Copy {
  fn new(n: usize, opr: fn(T, T) -> T, e: T) -> Self {
    let mut ofs = 1usize;
    while ofs < n {
      ofs <<= 1;
    }

    Self {
      id: e,
      node: vec![e; (ofs << 1) - 1],
      offset: ofs - 1,
      op: opr,
    }
  }

  fn update(&mut self, i: usize, x: T) {
    let mut cur = i + self.offset;
    assert!(cur < self.node.len());

    self.node[cur] = x;
    while cur > 0 {
      cur = (cur - 1) >> 1;
      self.node[cur] = (self.op)(self.node[(cur << 1) + 1], self.node[(cur << 1) + 2]);
    }
  }
  
  fn query(&self, l: usize, r: usize) -> T {
    let mut l = l + self.offset;
    let mut r = r + self.offset;
    assert!(l >= self.offset && r < self.node.len());

    let mut res = self.id;
    while l < r {
      if l & 1 == 0 {
        res = (self.op)(res, self.node[l]);
      }
      if r & 1 == 0 {
        res = (self.op)(res, self.node[r - 1]);
      }

      l = l >> 1;
      r = (r - 1) >> 1;
    }

    res
  }
}