Longest Increasing Sequence

Question

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Have you met this question in a real interview? Yes Example For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3

For [4, 2, 4, 5, 3, 7], the LIS is [4, 4, 5, 7], return 4

Challenge Time complexity O(n^2) or O(nlogn)

Clarification

What's the definition of longest increasing subsequence?

* The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.  

Thoughts

首先要注意LIS的定义,不是连续的 dp[i]表示以i为结尾的LIS的长度,对每一个i,loop i之前的所有j, 如果dp[j] + 1 > dp[i]就应该update

Challenge? O(n^2) -> O(nlogn) 另一个array b[], b[i]表示长度为i的LIS最后一个数最小可以是多少 解法

Solution

class Solution:             
    """                     
    @param nums: The integer array
    @return: The length of LIS (longest increasing subsequence)
    """                     
    def longestIncreasingSubsequence(self, nums):
        # write your code here
        if not nums:        
            return 0        
        length = len(nums)  
        max = 1             
        dp = [1 for i in range(length)]
        for i in range(1, length):
            for j in range(i):
                if nums[i] >= nums[j] and dp[i] < 1 + dp[j]:
                    dp[i] = dp[j] + 1
                    if dp[i] > max:
                        max = dp[i]
        return max