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)

pub mod segment_tree {
    pub struct SegmentTree<T, F> {
        seg: Vec<T>,
        n: usize,
        f: F,
        init_value: T,
    }
    impl<T: Copy, F: Fn(T, T) -> T> SegmentTree<T, F> {
        pub fn new(n: usize, init_value: T, f: F) -> SegmentTree<T, F> {
            let mut m = 1;
            while m <= n {
                m <<= 1;
            }
            SegmentTree {
                seg: vec![init_value; 2 * m],
                n: m,
                f: f,
                init_value: init_value,
            }
        }
        pub fn update(&mut self, k: usize, value: T) {
            let mut k = k;
            k += self.n - 1;
            self.seg[k] = value;
            while k > 0 {
                k = (k - 1) >> 1;
                self.seg[k] = (self.f)(self.seg[2 * k + 1], self.seg[2 * k + 2]);
            }
        }
        //Get a query result in the range [left, right)
        pub fn query(&self, left: usize, right: usize) -> T {
            assert!(left < right);
            self.query_range(left, right, 0, 0, self.n)
        }
        fn query_range(
            &self,
            left: usize,
            right: usize,
            k: usize,
            left_bound: usize,
            right_bound: usize,
        ) -> T {
            if right_bound <= left || right <= left_bound {
                self.init_value
            } else if left <= left_bound && right_bound <= right {
                self.seg[k]
            } else {
                let x = self.query_range(
                    left,
                    right,
                    2 * k + 1,
                    left_bound,
                    (left_bound + right_bound) >> 1,
                );
                let y = self.query_range(
                    left,
                    right,
                    2 * k + 2,
                    (left_bound + right_bound) >> 1,
                    right_bound,
                );
                (self.f)(x, y)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::segment_tree::SegmentTree;
    use rand::{thread_rng, Rng};

    #[test]
    fn random_update() {
        let n = 1000;
        //max segment tree
        let mut seg = SegmentTree::new(n, 0, |a, b| std::cmp::max(a, b));
        let mut v = vec![0; n];
        for _ in 0..10000 {
            let value = thread_rng().gen_range(0, 1000);
            let k = thread_rng().gen_range(0, n);
            v[k] = value;
            seg.update(k, value);
            //[0, n)
            assert_eq!(seg.query(0, n), *v.iter().max().unwrap());

            let l = thread_rng().gen_range(0, n);
            let r = thread_rng().gen_range(l, n);
            //two point
            //[l, r + 1)
            let x = v.iter().skip(l).take(r - l + 1).max().unwrap();
            assert_eq!(seg.query(l, r + 1), *x);
        }
    }
}

const MAX_A: usize = 300100;
#[derive(Default)]
//NOTE
//declare variables to reduce the number of parameters for dp and dfs etc.
struct Solver {}

impl Solver {
    fn solve(&mut self) {
        let stdin = std::io::stdin();
        let mut scn = Scanner {
            stdin: stdin.lock(),
        };
        let n: usize = scn.read();
        let k: usize = scn.read();
        let a: Vec<usize> = scn.vec(n);
        let mut seg = segment_tree::SegmentTree::new(MAX_A, 0, |a, b| std::cmp::max(a, b));

        for &x in a.iter() {
            let left = if k > x { 0 } else { x - k };
            let right = if x + k > MAX_A { MAX_A - 10 } else { x + k };
            let res = seg.query(left, right + 1);
            seg.update(x, res + 1);
        }
        let result = seg.query(0, MAX_A);
        println!("{}", result);
    }
}

fn main() {
    std::thread::Builder::new()
        .stack_size(64 * 1024 * 1024) // 64MB
        .spawn(|| {
            let mut solver = Solver::default();
            solver.solve()
        })
        .unwrap()
        .join()
        .unwrap();
}
pub mod utils {
    const DYX: [(isize, isize); 8] = [
        (0, 1),   //right
        (1, 0),   //down
        (0, -1),  //left
        (-1, 0),  //top
        (1, 1),   //down right
        (-1, 1),  //top right
        (1, -1),  //down left
        (-1, -1), //top left
    ];

    pub fn try_adj(y: usize, x: usize, dir: usize, h: usize, w: usize) -> Option<(usize, usize)> {
        let ny = y as isize + DYX[dir].0;
        let nx = x as isize + DYX[dir].1;
        if ny >= 0 && nx >= 0 {
            let ny = ny as usize;
            let nx = nx as usize;
            if ny < h && nx < w {
                Some((ny, nx))
            } else {
                None
            }
        } else {
            None
        }
    }
}

//snippet from kenkoooo
pub struct Scanner<R> {
    stdin: R,
}

impl<R: std::io::Read> Scanner<R> {
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn read_line(&mut self) -> String {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b'\n' || b == b'\r')
            .take_while(|&b| b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }

    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}