leetcode_300
Given an unsorted array of integers, find the length of longest increasing subsequence.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up:
Could you improve it to O(n log n) time complexity?
Solutions
dynamic programming O(n2)
dp[i]
represents the length of the longest increasing subsequence withins[:i]
binary search O(nlog(n))
Hard to prove the correctness, here is my thought:
tails[i]
represents the minumum tail element among all increasing subsequences with lengthi + 1
.There are two situations when looping through the sequence:
The current number is larger than the tail of
tails
: Pushing it at the back repsents the newly found increasing subsequence with longer length.The current number is smaller than the tail: Use binary search to find the correct point in
tails
and replace the first larger/equal one with the current number. This step does not change the correctness oftails
(invariant).
Last updated
Was this helpful?