You are given an integer array nums and an integer k. Your task is to find the longest subsequence that satisfies two important conditions:
- The subsequence is strictly increasing
- The difference between any two adjacent elements in the subsequence is at most k
A subsequence is derived from the original array by deleting some or no elements without changing the order of the remaining elements. For example, from array [4,2,1,4,3,4,5,8,15], a valid subsequence could be [2,4,5,8].
Return the length of the longest subsequence that meets both requirements.
Example: If nums = [4,2,1,4,3,4,5,8,15] and k = 3, one possible longest increasing subsequence with difference ⤠3 could be [1,3,4,5,8] with length 5.
Input & Output
Visualization
Time & Space Complexity
Coordinate compression O(n log n) + n operations on segment tree O(log n) each
Segment tree and coordinate compression arrays
Constraints
- 1 ⤠nums.length ⤠105
- 1 ⤠nums[i], k ⤠105
- The array can contain duplicate values
- Subsequence must be strictly increasing (no equal elements)