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 Ruby (2.7.1) (judge verdict: Wrong Answer)

require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7

class SegmentTree
  attr_accessor :a
  def initialize(nums)
    return if nums.nil? || nums.empty?
    size = nums.size
    @n = 1
    while @n < size
      @n <<= 1
    end
    @a = Array.new(@n*2-1){new_obj}

    size.times do |i|
      @a[@n + i - 1] = new_obj(nums[i])
    end
    (@n-2).downto(0) do |i|
      @a[i] = compare(@a[i*2+1], @a[i*2+2])
    end
  end

  def update(i, val)
    i += @n - 1
    @a[i] = new_obj(val)
    while i > 0
      i = (i-1)/2
      @a[i] = compare(@a[i*2+1], @a[i*2+2])
    end
  end

  def query(a, b, k=0, l=0, r=-1)
    r = @n-1 if r < 0
    return new_obj if b < l || r < a # not cover
    return @a[k]   if a <= l && r <= b # cover all

    lvalue = query(a, b, 2*k+1, l, (l+r)/2)
    rvalue = query(a, b, 2*k+2, (l+r)/2+1, r)
    return compare(lvalue, rvalue)
  end

  def compare(x, y)
    [x, y].max
  end

  def new_obj(obj=nil)
    obj || 0
  end
end

n,k = gets.chomp.split.map(&:to_i)

init_a = Array.new(300_001, 0)
st = SegmentTree.new(init_a)
n.times do
  num= gets.chomp.to_i
  max = st.query([num - k, 0].max, [num + k, 300_000].min)
  st.update(num, max + 1)
end

puts st.query(0, n)