Longest Increasing Subsequence II - Problem
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
example_1.py — Basic Case
$
Input:
nums = [4,2,1,4,3,4,5,8,15], k = 3
›
Output:
5
💡 Note:
One possible longest increasing subsequence is [1,3,4,5,8] with length 5. Each adjacent pair has difference ≤ 3: 3-1=2, 4-3=1, 5-4=1, 8-5=3.
example_2.py — Small Difference
$
Input:
nums = [7,4,5,1,8,12,4,7], k = 5
›
Output:
4
💡 Note:
One possible longest increasing subsequence is [4,5,7,12] with length 4. Differences: 5-4=1, 7-5=2, 12-7=5 (all ≤ 5).
example_3.py — Edge Case
$
Input:
nums = [1,5], k = 1
›
Output:
1
💡 Note:
Cannot form increasing subsequence of length > 1 because 5-1=4 > k=1. Maximum length is 1.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i], k ≤ 105
- The array can contain duplicate values
- Subsequence must be strictly increasing (no equal elements)
Visualization
Tap to expand
Understanding the Visualization
1
Scan Array
Process each element from left to right
2
Find Valid Range
For current element x, find all previous elements in range [x-k, x-1]
3
Get Maximum
Query the maximum subsequence length ending in the valid range
4
Update Tree
Update data structure with new maximum length at current position
Key Takeaway
🎯 Key Insight: Use segment tree with coordinate compression to efficiently query the maximum subsequence length in any value range, reducing time complexity from O(n²) to O(n log n).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code