Longest Increasing Subsequence

1 minute read

300. Longest Increasing Subsequence

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

Example 1:

Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Example 2:

Input: nums = [0,1,0,3,2,3]
Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]
Output: 1

Constraints:

  • 1 <= nums.length <= 2500
  • -104 <= nums[i] <= 104

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

Analysis

​ The problem can be divided into the small problems. Suppose we have the definition of dfs(i) which stands for the longest increasing subsequence, then we can deduce that

\[dfs(i) = max(df(j)) + 1 \;\;\;\; \text{ s[i] < s[j]}\]

​ For example, we have a sequence [10,9,2,5,3,7,101,18] and current end index i is 7, then dfs(7) is

\[dfs(7) = max(dfs(0), dfs(1), dfs(2), dfs(3), dfs(4), dfs(5)) + 1\]

​ We can also deduce the DP function:

\[f[i] = max(f[j], f[i]) + 1 \;\;\;\;\text{s[i] < s[j]}\]

Solutions

1. DFS way

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        @cache
        def dfs(i):
            res = 0
            for j in range(i):
                if nums[j] < nums[i]:
                    res= max(res, dfs(j))
            return res + 1
        ans = 0 
        for i in range(n):
            ans = max(ans, dfs(i))
        return ans

Input: [10,9,2,5,3,7,101,18]

output:

4

Complexity

  • Time complexity: ( O(n^2) ), where ( n ) is the length of the array.
  • Space complexity: ( O(n) ), where ( n) is the length of the array.

2. DP

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        f = [0] * (n)
        for i in range(n):
        	for j in range(i):
                if nums[j] < nums[i]:
                    f[i] = max(f[i], f[j])
            f[i] += 1
        return max(f)

Input: [10,9,2,5,3,7,101,18]

output:

4

Complexity

  • Time complexity: ( O(n^2) ), where ( n ) is the length of the array.
  • Space complexity: ( O(n) ), where ( n) is the length of the array.

Comments