MediumLeetCode #300Dynamic Programming
Longest Increasing Subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence.
Constraints
1 <= nums.length <= 2500, -10^4 <= nums[i] <= 10^4
Given an integer array nums, return the length of the longest strictly increasing subsequence.
1 <= nums.length <= 2500, -10^4 <= nums[i] <= 10^4
O(n²) DP: dp[i] = max(dp[j] + 1) for j < i where nums[j] < nums[i]. O(n log n): maintain sorted list of smallest tails and use binary search.
def lengthOfLIS(nums):
tails = []
for num in nums:
left, right = 0, len(tails)
while left < right:
mid = (left + right) // 2
if tails[mid] < num:
left = mid + 1
else:
right = mid
if left == len(tails):
tails.append(num)
else:
tails[left] = num
return len(tails)