300. Longest Increasing Subsequence

# Medium(非常经典,一定要会)

Solution 1: time complex = O(n2)O(n^2)

  1. Define f[i], records the longest increasing subsequence ending with nums[i]

  2. Compute f[i] from index of 0, if nums[j] < nums[i] (j < i), f[i]=max(f[i], f[j]+1)

  3. Loop f[i] to find biggest value, return it

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        # edge case
        if len(nums) <= 1:
            return len(nums)
        
        f = [1]*len(nums) # f[i] means LIS ending with nums[i]
        for i in range(0, len(nums)):
            for j in range(0, i):
                if nums[j] < nums[i]:
                    f[i] = max(f[i], f[j]+1)
        
        result = f[0]
        for i in range(1, len(f)):
            if f[i] > result:
                result = f[i]
                
        return result

Solution 2: time complex = O(nlgn)O(nlgn)

Save time when looking for the biggest element nums[j] less than nums[i] by binary search.

Last updated

Was this helpful?