In this problem, you are given an array of integers. You need to find the length of the longest subsequence such that the absolute difference between adjacent elements in the subsequence is strictly decreasing (or non-increasing, depending on the exact variant). For example, if differences are 5, then 3, then 1, the condition holds.
This question is a deep test of Dynamic Programming. Interviewers ask it to evaluate if a candidate can track multiple states simultaneously. Unlike standard LIS (Longest Increasing Subsequence) where you only care about the previous value, here you must track BOTH the previous value AND the previous difference. It highlights a candidate's ability to model complex 2D DP states effectively.
This problem relies on a 2D Dynamic Programming pattern. We define dp[i][diff] as the maximum length of a valid subsequence ending at index i with an absolute difference of exactly diff between nums[i] and the element before it. To calculate this, we iterate through previous indices j, calculate current_diff = abs(nums[i] - nums[j]), and then look for the maximum dp[j][prev_diff] where prev_diff >= current_diff.
Assume nums = [10, 5, 8, 7].
[10, 5]. Length = 2. dp[5_idx][5] = 2.[10, 5] had a diff of 5. Since , we can append 8! Sequence becomes [10, 5, 8]. Length = 3.[10, 5, 8] had a diff of 3. Since , we can append 7! Sequence becomes [10, 5, 8, 7]. Length = 4.
The longest sequence is 4.The most frequent mistake is using a simple 1D DP array, which simply doesn't hold enough information. You cannot determine if you are allowed to append a number without knowing the last gap established. Another mistake is using nested loops that iterate through all previous differences, resulting in time, which can trigger Time Limit Exceeded if not optimized by keeping track of running maximums.
For this interview pattern, get very comfortable with dictionary-based DP or 2D DP arrays where the second dimension represents a "constraint" or a "score" (like the difference). When the transition of a DP state depends on a property of the edge connecting two elements rather than just the elements themselves, a 2D state is mandatory.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Inverse Coin Change | Medium | Solve | |
| Maximize Total Cost of Alternating Subarrays | Medium | Solve | |
| Minimum Increment Operations to Make Array Beautiful | Medium | Solve | |
| Zero Array Transformation IV | Medium | Solve | |
| Best Time to Buy and Sell Stock V | Medium | Solve |