[NeetCode 150] Longest Increasing Subsequence

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 d p [ i ] dp[i] dp[i] denotes the minimum last number of increasing subsequence of length i i i. Obviously, d p dp dp will be an ascending array. To maintain d p dp dp, we need to find the index of last number that less than current number l l l, and add current number at the end to update d p [ l + 1 ] dp[l+1] dp[l+1].

Because d p dp dp is an ascending array, we can apply binary search to accelerate the search, which makes the whole solution O ( n log ⁡ n ) 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值