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)

// The main code is at the very bottom.

#[allow(unused_imports)]
use {
  lib::byte::ByteChar,
  std::cell::{Cell, RefCell},
  std::cmp::{
    self,
    Ordering::{self, *},
    Reverse,
  },
  std::collections::*,
  std::convert::identity,
  std::fmt::{self, Debug, Display, Formatter},
  std::io::prelude::*,
  std::iter::{self, FromIterator},
  std::marker::PhantomData,
  std::mem,
  std::num::Wrapping,
  std::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive},
  std::process,
  std::rc::Rc,
  std::thread,
  std::time::{Duration, Instant},
  std::{char, f32, f64, i128, i16, i32, i64, i8, isize, str, u128, u16, u32, u64, u8, usize},
};

#[allow(unused_imports)]
#[macro_use]
pub mod lib {
  pub mod byte {
    pub use self::byte_char::*;

    mod byte_char {
      use std::error::Error;
      use std::fmt::{self, Debug, Display, Formatter};
      use std::str::FromStr;

      #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
      #[repr(transparent)]
      pub struct ByteChar(pub u8);

      impl Debug for ByteChar {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          write!(f, "b'{}'", self.0 as char)
        }
      }

      impl Display for ByteChar {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          write!(f, "{}", self.0 as char)
        }
      }

      impl FromStr for ByteChar {
        type Err = ParseByteCharError;

        fn from_str(s: &str) -> Result<ByteChar, ParseByteCharError> {
          match s.as_bytes().len() {
            1 => Ok(ByteChar(s.as_bytes()[0])),
            0 => Err(ParseByteCharErrorKind::EmptyStr.into()),
            _ => Err(ParseByteCharErrorKind::TooManyBytes.into()),
          }
        }
      }

      #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
      pub struct ParseByteCharError {
        kind: ParseByteCharErrorKind,
      }

      impl Display for ParseByteCharError {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          f.write_str(match self.kind {
            ParseByteCharErrorKind::EmptyStr => "empty string",
            ParseByteCharErrorKind::TooManyBytes => "too many bytes",
          })
        }
      }

      impl Error for ParseByteCharError {}

      #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
      enum ParseByteCharErrorKind {
        EmptyStr,
        TooManyBytes,
      }

      impl From<ParseByteCharErrorKind> for ParseByteCharError {
        fn from(kind: ParseByteCharErrorKind) -> ParseByteCharError {
          ParseByteCharError { kind }
        }
      }
    }
  }

  pub mod io {
    pub use self::scanner::*;

    mod scanner {
      use std::io::{self, BufRead};
      use std::iter;
      use std::str::FromStr;

      #[derive(Debug)]
      pub struct Scanner<R> {
        reader: R,
        buf: String,
        pos: usize,
      }

      impl<R: BufRead> Scanner<R> {
        pub fn new(reader: R) -> Self {
          Scanner {
            reader,
            buf: String::new(),
            pos: 0,
          }
        }

        pub fn next(&mut self) -> io::Result<&str> {
          let start = loop {
            match self.rest().find(|c| c != ' ') {
              Some(i) => break i,
              None => self.fill_buf()?,
            }
          };
          self.pos += start;
          let len = self.rest().find(' ').unwrap_or(self.rest().len());
          let s = &self.buf[self.pos..][..len]; // self.rest()[..len]
          self.pos += len;
          Ok(s)
        }

        pub fn parse_next<T>(&mut self) -> io::Result<Result<T, T::Err>>
        where
          T: FromStr,
        {
          Ok(self.next()?.parse())
        }

        pub fn parse_next_n<T>(&mut self, n: usize) -> io::Result<Result<Vec<T>, T::Err>>
        where
          T: FromStr,
        {
          iter::repeat_with(|| self.parse_next()).take(n).collect()
        }

        pub fn map_next_bytes<T, F>(&mut self, mut f: F) -> io::Result<Vec<T>>
        where
          F: FnMut(u8) -> T,
        {
          Ok(self.next()?.bytes().map(&mut f).collect())
        }

        pub fn map_next_bytes_n<T, F>(&mut self, n: usize, mut f: F) -> io::Result<Vec<Vec<T>>>
        where
          F: FnMut(u8) -> T,
        {
          iter::repeat_with(|| self.map_next_bytes(&mut f))
            .take(n)
            .collect()
        }

        fn rest(&self) -> &str {
          &self.buf[self.pos..]
        }

        fn fill_buf(&mut self) -> io::Result<()> {
          self.buf.clear();
          self.pos = 0;
          let read = self.reader.read_line(&mut self.buf)?;
          if read == 0 {
            return Err(io::ErrorKind::UnexpectedEof.into());
          }
          if *self.buf.as_bytes().last().unwrap() == b'\n' {
            self.buf.pop();
          }
          Ok(())
        }
      }
    }
  }
}

pub mod ac_library_rs {
  //https://github.com/rust-lang-ja/ac-library-rs

  pub mod internal_bit {
    // Skipped:
    //
    // - `bsf` = `__builtin_ctz`: is equivalent to `{integer}::trailing_zeros`

    #[allow(dead_code)]
    pub(crate) fn ceil_pow2(n: u32) -> u32 {
      32 - n.saturating_sub(1).leading_zeros()
    }
  }
  pub mod internal_type_traits {
    use std::{
      fmt,
      iter::{Product, Sum},
      ops::{
        Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div,
        DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub,
        SubAssign,
      },
    };

    // Skipped:
    //
    // - `is_signed_int_t<T>`   (probably won't be used directly in `modint.rs`)
    // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`)
    // - `to_unsigned_t<T>`     (not used in `fenwicktree.rs`)

    /// Corresponds to `std::is_integral` in C++.
    // We will remove unnecessary bounds later.
    //
    // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the
    // same way as the original ACL.
    pub trait Integral:
      'static
      + Send
      + Sync
      + Copy
      + Ord
      + Not<Output = Self>
      + Add<Output = Self>
      + Sub<Output = Self>
      + Mul<Output = Self>
      + Div<Output = Self>
      + Rem<Output = Self>
      + AddAssign
      + SubAssign
      + MulAssign
      + DivAssign
      + RemAssign
      + Sum
      + Product
      + BitOr<Output = Self>
      + BitAnd<Output = Self>
      + BitXor<Output = Self>
      + BitOrAssign
      + BitAndAssign
      + BitXorAssign
      + Shl<Output = Self>
      + Shr<Output = Self>
      + ShlAssign
      + ShrAssign
      + fmt::Display
      + fmt::Debug
      + fmt::Binary
      + fmt::Octal
      + Zero
      + One
      + BoundedBelow
      + BoundedAbove
    {
    }

    /// Class that has additive identity element
    pub trait Zero {
      /// The additive identity element
      fn zero() -> Self;
    }

    /// Class that has multiplicative identity element
    pub trait One {
      /// The multiplicative identity element
      fn one() -> Self;
    }

    pub trait BoundedBelow {
      fn min_value() -> Self;
    }

    pub trait BoundedAbove {
      fn max_value() -> Self;
    }

    macro_rules! impl_integral {
      ($($ty:ty),*) => {
        $(
          impl Zero for $ty {
            #[inline]
            fn zero() -> Self {
              0
            }
          }

          impl One for $ty {
            #[inline]
            fn one() -> Self {
              1
            }
          }

          impl BoundedBelow for $ty {
            #[inline]
            fn min_value() -> Self {
              Self::min_value()
            }
          }

          impl BoundedAbove for $ty {
            #[inline]
            fn max_value() -> Self {
              Self::max_value()
            }
          }

          impl Integral for $ty {}
        )*
      };
    }

    impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
  }
  pub mod segtree {
    use crate::ac_library_rs::internal_bit::ceil_pow2;
    use crate::ac_library_rs::internal_type_traits::{BoundedAbove, BoundedBelow, One, Zero};
    use std::cmp::{max, min};
    use std::convert::Infallible;
    use std::marker::PhantomData;
    use std::ops::{Add, Mul};

    // TODO Should I split monoid-related traits to another module?
    pub trait Monoid {
      type S: Clone;
      fn identity() -> Self::S;
      fn binary_operation(a: &Self::S, b: &Self::S) -> Self::S;
    }

    pub struct Max<S>(Infallible, PhantomData<fn() -> S>);
    impl<S> Monoid for Max<S>
    where
      S: Copy + Ord + BoundedBelow,
    {
      type S = S;
      fn identity() -> Self::S {
        S::min_value()
      }
      fn binary_operation(a: &Self::S, b: &Self::S) -> Self::S {
        max(*a, *b)
      }
    }

    pub struct Min<S>(Infallible, PhantomData<fn() -> S>);
    impl<S> Monoid for Min<S>
    where
      S: Copy + Ord + BoundedAbove,
    {
      type S = S;
      fn identity() -> Self::S {
        S::max_value()
      }
      fn binary_operation(a: &Self::S, b: &Self::S) -> Self::S {
        min(*a, *b)
      }
    }

    pub struct Additive<S>(Infallible, PhantomData<fn() -> S>);
    impl<S> Monoid for Additive<S>
    where
      S: Copy + Add<Output = S> + Zero,
    {
      type S = S;
      fn identity() -> Self::S {
        S::zero()
      }
      fn binary_operation(a: &Self::S, b: &Self::S) -> Self::S {
        *a + *b
      }
    }

    pub struct Multiplicative<S>(Infallible, PhantomData<fn() -> S>);
    impl<S> Monoid for Multiplicative<S>
    where
      S: Copy + Mul<Output = S> + One,
    {
      type S = S;
      fn identity() -> Self::S {
        S::one()
      }
      fn binary_operation(a: &Self::S, b: &Self::S) -> Self::S {
        *a * *b
      }
    }

    impl<M: Monoid> Default for Segtree<M> {
      fn default() -> Self {
        Segtree::new(0)
      }
    }
    impl<M: Monoid> Segtree<M> {
      pub fn new(n: usize) -> Segtree<M> {
        vec![M::identity(); n].into()
      }
    }
    impl<M: Monoid> From<Vec<M::S>> for Segtree<M> {
      fn from(v: Vec<M::S>) -> Self {
        let n = v.len();
        let log = ceil_pow2(n as u32) as usize;
        let size = 1 << log;
        let mut d = vec![M::identity(); 2 * size];
        d[size..(size + n)].clone_from_slice(&v);
        let mut ret = Segtree { n, size, log, d };
        for i in (1..size).rev() {
          ret.update(i);
        }
        ret
      }
    }
    impl<M: Monoid> Segtree<M> {
      pub fn set(&mut self, mut p: usize, x: M::S) {
        assert!(p < self.n);
        p += self.size;
        self.d[p] = x;
        for i in 1..=self.log {
          self.update(p >> i);
        }
      }

      pub fn get(&self, p: usize) -> M::S {
        assert!(p < self.n);
        self.d[p + self.size].clone()
      }

      pub fn prod(&self, mut l: usize, mut r: usize) -> M::S {
        assert!(l <= r && r <= self.n);
        let mut sml = M::identity();
        let mut smr = M::identity();
        l += self.size;
        r += self.size;

        while l < r {
          if l & 1 != 0 {
            sml = M::binary_operation(&sml, &self.d[l]);
            l += 1;
          }
          if r & 1 != 0 {
            r -= 1;
            smr = M::binary_operation(&self.d[r], &smr);
          }
          l >>= 1;
          r >>= 1;
        }

        M::binary_operation(&sml, &smr)
      }

      pub fn all_prod(&self) -> M::S {
        self.d[1].clone()
      }

      pub fn max_right<F>(&self, mut l: usize, f: F) -> usize
      where
        F: Fn(&M::S) -> bool,
      {
        assert!(l <= self.n);
        assert!(f(&M::identity()));
        if l == self.n {
          return self.n;
        }
        l += self.size;
        let mut sm = M::identity();
        while {
          // do
          while l % 2 == 0 {
            l >>= 1;
          }
          if !f(&M::binary_operation(&sm, &self.d[l])) {
            while l < self.size {
              l *= 2;
              let res = M::binary_operation(&sm, &self.d[l]);
              if f(&res) {
                sm = res;
                l += 1;
              }
            }
            return l - self.size;
          }
          sm = M::binary_operation(&sm, &self.d[l]);
          l += 1;
          // while
          {
            let l = l as isize;
            (l & -l) != l
          }
        } {}
        self.n
      }

      pub fn min_left<F>(&self, mut r: usize, f: F) -> usize
      where
        F: Fn(&M::S) -> bool,
      {
        assert!(r <= self.n);
        assert!(f(&M::identity()));
        if r == 0 {
          return 0;
        }
        r += self.size;
        let mut sm = M::identity();
        while {
          // do
          r -= 1;
          while r > 1 && r % 2 == 1 {
            r >>= 1;
          }
          if !f(&M::binary_operation(&self.d[r], &sm)) {
            while r < self.size {
              r = 2 * r + 1;
              let res = M::binary_operation(&self.d[r], &sm);
              if f(&res) {
                sm = res;
                r -= 1;
              }
            }
            return r + 1 - self.size;
          }
          sm = M::binary_operation(&self.d[r], &sm);
          // while
          {
            let r = r as isize;
            (r & -r) != r
          }
        } {}
        0
      }

      fn update(&mut self, k: usize) {
        self.d[k] = M::binary_operation(&self.d[2 * k], &self.d[2 * k + 1]);
      }
    }

    // Maybe we can use this someday
    // ```
    // for i in 0..=self.log {
    //     for j in 0..1 << i {
    //         print!("{}\t", self.d[(1 << i) + j]);
    //     }
    //     println!();
    // }
    // ```

    pub struct Segtree<M>
    where
      M: Monoid,
    {
      // variable name is _n in original library
      n: usize,
      size: usize,
      log: usize,
      d: Vec<M::S>,
    }
  }
}

#[allow(unused_macros)]
macro_rules! eprint {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::eprint!($($arg)*)
    }
  };
}
#[allow(unused_macros)]
macro_rules! eprintln {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::eprintln!($($arg)*)
    }
  };
}
#[allow(unused_macros)]
macro_rules! dbg {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::dbg!($($arg)*)
    } else {
      ($($arg)*)
    }
  };
}

const CUSTOM_STACK_SIZE_MIB: Option<usize> = Some(1024);
const INTERACTIVE: bool = false;

fn main() -> std::io::Result<()> {
  match CUSTOM_STACK_SIZE_MIB {
    Some(stack_size_mib) => std::thread::Builder::new()
      .name("run_solver".to_owned())
      .stack_size(stack_size_mib * 1024 * 1024)
      .spawn(run_solver)?
      .join()
      .unwrap(),
    None => run_solver(),
  }
}

fn run_solver() -> std::io::Result<()> {
  let stdin = std::io::stdin();
  let reader = stdin.lock();
  let stdout = std::io::stdout();
  let writer = stdout.lock();
  macro_rules! with_wrapper {
    ($($wrapper:expr)?) => {{
      let mut writer = $($wrapper)?(writer);
      solve(reader, &mut writer)?;
      writer.flush()
    }};
  }
  if cfg!(debug_assertions) || INTERACTIVE {
    with_wrapper!()
  } else {
    with_wrapper!(std::io::BufWriter::new)
  }
}

fn solve<R, W>(reader: R, mut writer: W) -> std::io::Result<()>
where
  R: BufRead,
  W: Write,
{
  let mut _scanner = lib::io::Scanner::new(reader);
  #[allow(unused_macros)]
  macro_rules! scan {
    ($T:ty) => {
      _scanner.parse_next::<$T>()?.unwrap()
    };
    ($($T:ty),+) => {
      ($(scan!($T)),+)
    };
    ($T:ty; $n:expr) => {
      _scanner.parse_next_n::<$T>($n)?.unwrap()
    };
    ($($T:ty),+; $n:expr) => {
      iter::repeat_with(|| -> std::io::Result<_> { Ok(($(scan!($T)),+)) })
        .take($n)
        .collect::<std::io::Result<Vec<_>>>()?
    };
  }
  #[allow(unused_macros)]
  macro_rules! scan_bytes_map {
    ($f:expr) => {
      _scanner.map_next_bytes($f)?
    };
    ($f:expr; $n:expr) => {
      _scanner.map_next_bytes_n($n, $f)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! print {
    ($($arg:tt)*) => {
      write!(writer, $($arg)*)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! println {
    ($($arg:tt)*) => {
      writeln!(writer, $($arg)*)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! answer {
    ($($arg:tt)*) => {{
      println!($($arg)*);
      return Ok(());
    }};
  }
  {
    use ac_library_rs::segtree::*;

    let (n, k) = scan!(usize, u64);
    let a = scan!(u64; n);

    let &a_max = a.iter().max().unwrap();
    let mut st = Segtree::<Max<usize>>::new((a_max + 1) as usize);
    for i in 0..n {
      let l = a[i].saturating_sub(k);
      let r = (a[i] + k).min(a_max as u64);
      let val = st.prod(l as usize, (r + 1) as usize);
      st.set(a[i] as usize, val + 1);
      dbg!(i, val + 1);
    }

    let ans = st.prod(0, (a_max + 1) as usize);
    println!("{}", ans);
  }
  #[allow(unreachable_code)]
  Ok(())
}