LeetCode 2407 Longest Increasing Subsequence II - Solution

The pattern

You use segment tree that stores max LIS ending at each value. Query range [nums[i]-k, nums[i]-1] for transitions.

What makes this work: for element with value v, LIS ending at it = 1 + max(LIS ending at values v-k to v-1). Segment tree handles range max query.

Example: nums = [4,2,1], k = 3. For 4: you query range [1,3], get max LIS, add 1.

Segment tree for range max queries. For n=105n = 10^5: O(nlogn)O(n \log n) time, about 1.7×1061.7 \times 10^6 operations. O(max(nums))O(\max(nums)) space.