300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.

 

 
Hide Similar Problems
 (M) Increasing Triplet Subsequence

 

O(n^2) Dynamic Programing Solution. This algorithm is able to give you what the sequence is.

public class Solution {
    public int lengthOfLIS(int[] nums) {
        if(nums.length == 0)
            return 0;
            
        int[] results = new int[nums.length];
        for(int i = nums.length-1; i>=0; --i)
        {
            results[i] = 1;
            for(int j=i+1;j<nums.length;++j)
            {
                if(nums[i]<nums[j] && results[i]<=results[j])
                {
                    results[i] = 1 + results[j];
                }
            }
        }
        
        int max = Integer.MIN_VALUE;
        for(int r: results)
        {
            if(max<r)
                max = r;
        }
        return max;
    }
}

 

 

O(nlog(n)). This solution can only tell you the length. The idea is to create a new array of sorted sequence, not necessary the correct one, the length is the same as the correct one.

For example, your input is:

new int[]{10, 9, 2, 5, 3, 7, 101, 1, 18}

The final dp array will be:

{1,3,7,18,0,0,0,0,0}

Code:

public class Solution {
    public int lengthOfLIS(int[] nums) {            
        int[] dp = new int[nums.length];
        int len = 0;

        for(int x : nums) {
            int i = Arrays.binarySearch(dp, 0, len, x);
            if(i < 0) i = -(i + 1);
            dp[i] = x;
            if(i == len) len++;
        }

        return len;
    }
}

 

posted @ 2016-06-03 14:09  新一代的天皇巨星  阅读(428)  评论(0)    收藏  举报