#K63792. Longest Subsequence with Minimum Index Gap
Longest Subsequence with Minimum Index Gap
Longest Subsequence with Minimum Index Gap
You are given a playlist of n songs represented as integers and a positive integer d. Your task is to find the length of the longest subsequence such that the absolute difference between the indices of any two consecutive songs in the subsequence is at least d.
In mathematical terms, if the indices of the songs chosen for the subsequence are \(i_1, i_2, \ldots, i_k\) with \(1 \le i_j \le n\), then for any consecutive pair \((i_j, i_{j+1})\) it must hold that:
\(i_{j+1} - i_j \ge d\)
Your goal is to compute the maximum possible value of k (the length of such a subsequence).
The solution involves using dynamic programming. Let \(dp[i]\) denote the length of the longest valid subsequence ending at index \(i\). You can recursively build the answer using the relation:
\(dp[i] = \max_{j < i \text{ and } (i - j \ge d)}\{dp[j] + 1\}\)
with the initial condition \(dp[i] = 1\) for all valid indices.
inputFormat
The input is given via standard input (stdin) and consists of two lines.
- The first line contains two integers n and d, where n is the number of songs in the playlist and d is the minimum required index gap.
- The second line contains n space-separated integers which represent the playlist.
outputFormat
The output should be written to standard output (stdout) and consists of a single integer: the length of the longest subsequence that satisfies the condition.
## sample7 2
1 2 3 4 5 6 7
4