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 proconio::input;
use std::cmp;

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

    let op = cmp::max;
    let mut rmq = RMQ::new(300010, 0, op);

    let mut ans = 0;
    for &na in &a {
        let l = if na >= k { na - k } else { 0 };
        let r = cmp::min(na + k, 300000);
        let tmp = rmq.query(l, r + 1, 0, 0, rmq.get_n()) + 1;
        ans = cmp::max(ans, tmp);
        rmq.update(na, tmp);
    }

    println!("{}", ans);
}

struct RMQ {
    n: usize,
    dat: Vec<usize>,
    e : usize,
    op: fn(usize, usize) -> usize,
}

impl RMQ {
    fn new(_n: usize, e: usize, op: fn(usize, usize) -> usize) -> Self {
        let mut n = 1;
        while n < _n {
            n *= 2;
        }

        RMQ {
            n: n,
            dat: vec![e; 2 * n - 1],
            e: e,
            op: op,
        }
    }

    fn update(&mut self, mut k: usize, a: usize) {
        //kを0-indexedに
        k += self.n - 1;
        self.dat[k] = a;
        while k > 0 {
            k = (k - 1) / 2;
            self.dat[k] = (self.op)(self.dat[k * 2 + 1], self.dat[k * 2 + 2]);
        }
    }

    /// queryは[a, b)の最大値を返す
    ///外から呼ぶときはquery(a, b, 0, 0, n)と呼ぶ
    fn query(&self, a: usize, b: usize, k: usize, l: usize, r: usize) -> usize {
        if r <= a || b <= l {
            return self.e;
        }
        if a <= l && r <= b {
            return self.dat[k];
        } else {
            let vl = self.query(a, b, k * 2 + 1, l, (l + r) / 2);
            let vr = self.query(a, b, k * 2 + 2, (l + r) / 2, r);
            return (self.op)(vl, vr);
        }
    }

    ///queryを呼ぶときに使う
    fn get_n(&self) -> usize {
        self.n
    }
}