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 PyPy3 (7.3.0) (judge verdict: Time Limit Exceeded)

import math

def getval():
    n,k = map(int,input().split())
    a = [int(input()) for i in range(n)]
    return n,k,a 

def main(n,k,a):
    t = [0 for i in range(2**20+1)]
    ans = 0
    for i in range(n):
        cur = a[i]
        floor = max(1,cur-k)
        ceil = min(cur+k,2**19)
        q = [1]
        temp = 1
        #print(cur,floor,ceil)
        while q:
            idx = q.pop(0)
            h = math.floor(math.log2(idx))
            curfloor = (idx-2**h) * 2**(19-h) + 1
            curceil = (idx-2**h+1) * 2**(19-h)
            nextceil = ((idx*2)-2**(h+1)+1) * 2**(19-(h+1))
            nextfloor = nextceil + 1
            #print(h,idx)
            #print(idx,curfloor,curceil,nextfloor,nextceil)
            if curfloor>=floor and curceil<=ceil:
                temp = max(temp,t[idx]+1)
                continue
            if nextceil>=floor and h<19:
                q.append(idx*2)
            if nextfloor<=ceil and h<19:
                q.append(idx*2+1)
            #t[idx] = max(t[idx],temp)
        idx = 1
        for h in range(20):
            t[idx] = max(t[idx],temp)
            idx *= 2
            nextceil = ((idx)-2**(h+1)+1) * 2**(19-(h+1))
            #print(nextceil)
            if cur>nextceil:
                idx += 1
    print(t[1])
        #print(t[2**19+2])
        

if __name__=="__main__":
    n,k,a = getval()
    main(n,k,a)