Problem Description
Given an array of integers nums, find the length of the longest subsequence seq such that the absolute differences between consecutive elements form a non-increasing sequence. In other words, for a subsequence seq0, seq1, seq2, …, seq_m, the condition |seq1 – seq0| >= |seq2 – seq1| >= … >= |seq_m – seq_(m-1)| must hold.
Key Insights
- This is a dynamic programming problem where you need to keep track not only of the subsequence length but also the last difference between consecutive elements.
- Using a DP state such as dp[i][d] to represent the length of the longest valid subsequence ending at index i with the last adjacent difference equal to d.
- When extending a valid subsequence ending at index i to include a new element at index j, compute the new difference. It must be no larger than the previous difference for the subsequence to remain valid.
- Since the values in nums are bounded (nums[i] <= 300), the possible differences are also limited, which helps in managing the state space.
Space and Time Complexity
Time Complexity: O(n^2 * D) in the worst case, where n is the number of elements in nums and D is the range of possible differences (which is small since nums[i] <= 300).
Space Complexity: O(n * D) for storing the DP state.
Solution
We use dynamic programming with a state dp[i][d] representing the maximum length of a valid subsequence ending at index i with its last adjacent difference equal to d. For every pair of indices (i, j) with i < j, we compute the absolute difference newDiff = |nums[j] – nums[i]|. Then, we consider all DP states from index i that have a previous difference (say currentDiff) such that newDiff <= currentDiff; this condition ensures that the sequence of differences stays non-increasing. We update dp[j][newDiff] accordingly. We also start a new valid pair (nums[i], nums[j]) by initializing dp[j][newDiff] to at least 2 if no previous state is extended. Finally, the answer is the maximum value found among all dp states.