0

I am working on the following leetcode problem:

Given an integer array nums, return the length of the longest strictly increasing subsequence.

The solution given is O(N^2) time but I have the following solution that does not work in it's current state:

   def lengthOfLIS(self, nums: List[int]) -> int:
        dp = [-1 for i in range(len(nums))]
        dp[0] = 1
        for i in range(1, len(nums)):
            if nums[i] > nums[i-1]:
                if i >= 2:
                    if dp[i] > dp[i-2]:
                        dp[i] = max(dp[i-1], dp[i-2], 0) + 1
                    else:
                        dp[i] = dp[i-1] + 1
                else:
                    dp[i] = dp[i-1] + 1
            else:
                dp[i] = 1
        return max(dp)

I am trying to get a O(N) solution (if it is possible but I am not sure!). My logic is as follows to choose dp[i] by either deleting an element if needed or picking it otherwise. Is it possible to fix my approach or should I bin it altoghether?

  • 1
    You can implement *quasilinear* `O(n * log(n))` algorithm: https://en.wikipedia.org/wiki/Longest_increasing_subsequence – Dmitry Bychenko Jul 07 '21 at 17:34
  • @DmitryBychenko does that mean that my code cannot be fixed? –  Jul 07 '21 at 17:44
  • Yours cannot pass the tests. Besides, it's just too slow... You can achieve O(nlog(n)) by employing binary search. Try it. – Daniel Hao Jul 07 '21 at 21:01

0 Answers0