Longest Increasing Subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from the given sequence by deleting some or no elements without changing the relative order of the remaining characters.
For example, “cat” is a subsequence of “crabt”.
Example 1:
Input: nums = [9,1,4,2,3,3,7]
Output: 4
Explanation: The longest increasing subsequence is [1,2,3,7], which has a length of 4.
Example 2:
Input: nums = [0,3,1,3,2,3]
Output: 4
Constraints:
1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
Solution
Let dp[i]dp[i]dp[i] denotes the minimum last number of increasing subsequence of length iii. Obviously, dpdpdp will be an ascending array. To maintain dpdpdp, we need to find the index of last number that less than current number lll, and add current number at the end to update dp[l+1]dp[l+1]dp[l+1].
Because dpdpdp is an ascending array, we can apply binary search to accelerate the search, which makes the whole solution O(nlogn)O(n\log n)O(nlogn) time complexity.
Code
class Solution:
def bs(self, nums, target, ri):
le = 0
pos = 0
while le <= ri:
mid = (le+ri)//2
if nums[mid] < target:
pos = mid
le = mid+1
else:
ri = mid-1
return pos
def lengthOfLIS(self, nums: List[int]) -> int:
dp = [1001]*(len(nums)+1)
dp[0] = -1001
ans = 0
for num in nums:
pos = self.bs(dp, num, ans)
dp[pos+1] = min(dp[pos+1], num)
ans = max(ans, pos+1)
return ans