#2407

Longest Increasing Subsequence II

Hard Segment tree over values (range max)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Find the longest strictly increasing subsequence where each pair of neighbouring elements differs by at most k.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest increasing subsequence where neighbouring values differ by at most k.

Why this works: best[v] = the longest run ending with value v. For x, ask the max of best over [x-k, x-1], a range max query on a segment tree.

Example: [4, 2, 1, 4, 3, 4, 5, 8, 15], k = 3

1 → 3 → 4 → 5 → 8 → length 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using the O(n²) LIS DP — too slow for n = 10^5.

Solve on LeetCode ↗
Complexity
  • Time: O(n log M).
  • Space: O(M).
Topic: Segment Tree, Fenwick & Sparse Table
🎬 Episodes 98–100: video coming soon