- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 62 lines of Python from the credited upstream file longest-increasing-subsequence-ii.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import bisect5 6 78class SegmentTree(object):9 def __init__(self, N,10 build_fn=lambda _: 0,11 query_fn=lambda x, y: y if x is None else x if y is None else max(x, y),12 update_fn=lambda x: x):13 self.tree = [None]*(2*2**((N-1).bit_length()))14 self.base = len(self.tree)215 self.query_fn = query_fn16 self.update_fn = update_fn17 for i in xrange(self.base, self.base+N):18 self.tree[i] = build_fn(i-self.base)19 for i in reversed(xrange(1, self.base)):20 self.tree[i] = query_fn(self.tree[2*i], self.tree[2*i+1])21 22 def update(self, i, h):23 x = self.base+i24 self.tree[x] = self.update_fn(h)25 while x > 1:26 x = 227 self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])28 29 def query(self, L, R):30 if L > R:31 return 032 L += self.base33 R += self.base34 left = right = None35 while L <= R:36 if L & 1:37 left = self.query_fn(left, self.tree[L])38 L += 139 if R & 1 == 0:40 right = self.query_fn(self.tree[R], right)41 R -= 142 L = 243 R = 244 return self.query_fn(left, right)45 46 4748class Solution(object):49 def lengthOfLIS(self, nums, k):50 """51 :type nums: List[int]52 :type k: int53 :rtype: int54 """55 sorted_nums = sorted({x-1 for x in nums})56 num_to_idx = {x:i for i, x in enumerate(sorted_nums)}57 st = SegmentTree(len(num_to_idx))58 for x in nums:59 x -= 160 st.update(num_to_idx[x], st.query(bisect.bisect_left(sorted_nums, x-k), num_to_idx[x]-1)+1)61 return st.tree[1] 62