progress

~/problems / 1-D dynamic programming / Longest increasing subsequence

LIS length ending at each index (O(n²) DP)

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Before the fast bisect method, learn the plain DP it speeds up.

Implement lis_ending_at(nums: list[int]) -> list[int]. Entry i is the length of the longest strictly increasing subsequence that ends with nums[i] (skip elements freely, but keep their order).

lis_ending_at([3, 1, 4, 1, 5, 9, 2, 6])  # [1, 1, 2, 1, 3, 4, 2, 4]
lis_ending_at([5, 5, 5])                 # [1, 1, 1]   equal values don't extend a subsequence

The longest increasing subsequence overall is then max(result).

Up to 2000 numbers, so O(n²) is expected. An empty list gives [].

Show hint

ends[i] = 1 + max(ends[j] for every j < i with nums[j] < nums[i]), or 1 if there is no such j.

Topic: Longest increasing subsequence. O(n log n) with tails[] + bisect; rebuild via parent pointers.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc