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)

lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

N = lines[0][0]
K = lines[0][1]

def max(x,y)
  if x > y then
    return x
  else
    return y
  end
end
  
def min(x,y)
  if x > y then
    return y
  else
    return x
  end
end

if K > 30 then

dp = []
for i in 1..N do
  low_last = 0
  high_last = 0
  num = lines[i][0]
  for j in 1..i-1 do
    if lines[i-j][0] < num and lines[i-j][0] + K >= num then
      low_last = dp[i-j-1]
      break
    end
  end
  for j in 1..i-1 do
    if lines[i-j][0] >= num and lines[i-j][0] <= num + K then
      high_last = dp[i-j-1]
      break
    end
  end
  if low_last < high_last then
    dp[i-1] = high_last + 1
  else
    dp[i-1] = low_last + 1
  end
end
    
dp_max = 0
for i in 1..N do
  if dp_max < dp[i-1] then
    dp_max = dp[i-1]
  end
end
puts dp_max
  
  
else

Inf = 3 * (10 ** 5)
  
dp = []
for i in 1..Inf do
  dp[i-1] = 0
end
  
for i in 1..N do
  num = lines[i][0]
  max_around = 0
  for j in max(1, num-K)..min(N, num+K) do
    if dp[j-1] > max_around then
      max_around = dp[j-1]
    end
  end
  dp[i-1] = max_around + 1
end

dp_max = 0
for i in 1..Inf do
  if dp_max < dp[i-1] then
    dp_max = dp[i-1]
  end
end
puts dp_max + 1

end