Problem Description
Given an integer array nums and an integer k, find the longest subsequence of nums that is strictly increasing and where the difference between any two adjacent elements is at most k. Return the length of such longest subsequence.
Key Insights
- The subsequence must be strictly increasing.
- The difference between two consecutive elements must be ≤ k.
- A dynamic programming approach can be used where we compute dp[x] as the length of the longest valid subsequence ending with a number x.
- To efficiently query the maximum dp value in a range (specifically, from [num - k, num - 1]), we can use a segment tree or BIT (Fenwick Tree).
- The problem constraints (n up to 10^5 and values up to 10^5) require an O(n log M) solution.
Space and Time Complexity
Time Complexity: O(n log M), where M is the maximum possible value (up to 10^5)
Space Complexity: O(M) (for the segment tree/BIT)
Solution
We iterate through the array nums. For each number, we want to find the maximum dp value for all valid previous numbers in the range [num - k, num - 1]. We then use that value plus one as the dp for the current number and update our data structure accordingly.
A segment tree is used because it allows us to efficiently query the maximum value in an arbitrary interval and update a single index. In our segment tree, each leaf represents a possible number value (from 1 to the maximum value in nums). For each num in the array, we:
- Compute leftBound = max(1, num - k) and rightBound = num - 1. If rightBound < leftBound we treat the best previous value as 0.
- Query the segment tree in the interval [leftBound, rightBound] to get the maximum dp value.
- Set current dp as (queried value + 1).
- Update the segment tree at index num with the maximum of its current value and the new dp.
- Keep track of the global maximum dp value across iterations.
This method guarantees that we are considering all valid previous subsequences that can extend to the current number while satisfying the constraints.