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: Time Limit Exceeded)

class SegTree
  attr_accessor(:node, :op, :e, :offset)
  
  def initialize(src = [], op, e)
    @op = op
    @e = e

    ofs = 1
    n = src.size
    while ofs < n
      ofs <<= 1
    end

    nd = Array.new(ofs - 1, @e)
    ofs.times do |i|
      nd << (src[i] || @e)
    end
    
    @node = nd # 0-indexed
    @offset = ofs # log2(n).ceil
    1.step(ofs - 1) do |i|
      update(-i, @e)
    end
  end

  def update(i, x) # 一点更新
    i += @offset - 1
    @node[i] = x
    
    while i > 0
      i = (i - 1) >> 1
      @node[i] = @op.call(@node[(i << 1) + 1], @node[(i << 1) + 2])
    end
  end

  def query(l, r) # [l, r)
    l += @offset - 1
    r += @offset - 1

    res = @e
    while l < r
      if l & 1 == 0
        res = @op.call(res, @node[l])
      end
      if r & 1 == 0
        res = @op.call(res, @node[r - 1])
      end
      l = l >> 1
      r = (r - 1) >> 1
    end
    return res
  end
end

m = 3 * (10 ** 5)
chmax = -> (x, y) { (x > y)? x : y }
n, k = $stdin.readline.chomp.split.map(&:to_i)
a = Array.new(m + 1, 0)
seg = SegTree.new(a, chmax, 0)

res = 0
n.times do
  a = $stdin.readline.to_i
  l = [0, a - k].max
  r = [m, a + k].min
  t = seg.query(l, r + 1) + 1
  res = (res < t)? t : res
  seg.update(a, t)
end
puts res