#C4881. Longest Arithmetic Subsequence with Constant Difference

    ID: 48468 Type: Default 1000ms 256MiB

Longest Arithmetic Subsequence with Constant Difference

Longest Arithmetic Subsequence with Constant Difference

Given an array of integers \(a_1, a_2, \ldots, a_n\) and an integer \(d\), find the length of the longest subsequence such that for any consecutive elements \(a_{i}\) and \(a_{j}\) in the subsequence, the following holds:

\(a_{j} - a_{i} = d\)

A subsequence is obtained by deleting some or no elements from the array while preserving the order of the remaining elements. Your task is to compute the maximum possible length of such a subsequence.

Example:

  • Input: n = 6, d = 2, arr = [1, 3, 5, 8, 6, 4]
  • Output: 3 (One possible subsequence is [1, 3, 5])

inputFormat

The first line contains an integer (T) representing the number of test cases. Each test case consists of two lines:

  1. The first line contains two integers (n) and (d), where (n) is the number of elements in the array and (d) is the required difference.
  2. The second line contains (n) space-separated integers representing the array elements.

For each test case, output the length of the longest subsequence satisfying the condition.

outputFormat

For each test case, print one integer per line — the length of the longest subsequence with the consecutive difference exactly equal to (d).## sample

2
6 2
1 3 5 8 6 4
5 -1
4 3 2 1 0
3

5

</p>