LeetCode 2407 Longest Increasing Subsequence II - Why Naive Fails

Why brute force fails

Standard LIS DP is O(n2)O(n^2). The constraint that consecutive elements differ by at most kk doesn't reduce this with naive approach.

Example: n=105n = 10^5, k=105k = 10^5. Standard LIS checks all j<ij < i where nums[j]<nums[i]nums[j] < nums[i]. Still O(n2)O(n^2).

Segment tree: for element with value vv, query max LIS among values [vk,v1][v-k, v-1]. Add 11 for current element. Update segment tree at position vv. Each operation is O(log(max(nums)))O(\log(\max(nums))).