Longest Increasing Subsequence
Examples
Example 1:
Input: nums = [9,1,4,2,3,3,7]
Output: 4
Explanation:
Example 2:
Input: nums = [0,3,1,3,2,3]
Output: 4
Example 1:
Input: nums = [9,1,4,2,3,3,7]
Output: 4
Explanation:
Example 2:
Input: nums = [0,3,1,3,2,3]
Output: 4
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.
"cat" is a subsequence of "crabt".The longest increasing subsequence is [1,2,3,7], which has a length of 4.
1 <= nums.length <= 1000-1000 <= nums[i] <= 1000Use patience sorting with a tails array. For each number, binary search the leftmost position in tails it can replace (first value >= num). If it is larger than all tails, append it. The length of tails is the LIS length.
tails[i] stores the smallest possible tail value for an increasing subsequence of length i + 1. Replacing with a smaller tail keeps future options open without reducing subsequence lengths. Therefore the final size of tails equals the LIS length.
O(n log n)O(n)class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
tails = []
for num in nums:
idx = bisect.bisect_left(tails, num)
if idx == len(tails):
tails.append(num)
else:
tails[idx] = num
return len(tails)