Segment tree over values
Time O(n log V) Space O(V)Iterative max segment tree of size max value + 1. For each x: best = query(max(0, x − k), x) (exclusive end), update x with best + 1.
nums = [4,2,1,4,3,4,5,8,15], k = 3Step 1/5Cells are values 1 to 8. 4, 2 and 1 find nothing smaller in their range, so each starts a chain of 1.
class Solution {
private int size;
private int[] t;
public int lengthOfLIS(int[] nums, int k) {
int max = 0;
for (int x : nums) max = Math.max(max, x);
size = max + 1;
t = new int[2 * size];
int best = 0;
for (int x : nums) {
int len = query(Math.max(0, x - k), x) + 1; // values in [x - k, x - 1]
update(x, len);
best = Math.max(best, len);
}
return best;
}
private void update(int i, int v) {
i += size;
if (t[i] >= v) return;
for (t[i] = v; i > 1; i >>= 1) t[i >> 1] = Math.max(t[i], t[i ^ 1]);
}
private int query(int l, int r) {
int res = 0;
for (l += size, r += size; l < r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) res = Math.max(res, t[l++]);
if ((r & 1) == 1) res = Math.max(res, t[--r]);
}
return res;
}
}Verdict: The tails trick doesn't handle the k limit; range max does.