CodeArchon

medium1-D Dynamic ProgrammingMicrosoftFacebook

Longest Ascending Trail

A biologist finds the longest run of ever-increasing specimen weights in a chronological log.

Given an integer array, return the length of the longest strictly increasing subsequence.

Choose approach

1
0
?
1
?
2
?
3
?
4
?
5
?
6
?
7
ipos
1/9
Narrationstep 1 of 9

x=10 → append at tails[0]. tails = [10] (len 1).

1def lengthOfLIS(nums):
2 from bisect import bisect_left
3 tails = []
4 for x in nums:
5 i = bisect_left(tails, x)
6 if i == len(tails): tails.append(x)
7 else: tails[i] = x
8 return len(tails)
Variables
i=0
x=10
pos=0
tailsLen=1

How to think about it

  1. O(n log n) solution uses patience sorting with binary search over tails.
  2. Final answer = max dp[i].

Edge cases to catch in interview

  • All descending -> 1.
  • Single element -> 1.

Examples

Example 14
{"nums":[0,1,0,3,2,3]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed