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 is4. 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(n^2) complexity.

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

Credits: Special thanks to@pbrotherarrow-up-rightfor adding this problem and creating all test cases.

Thoughts

Code Binary Search (Java) inspired by GeeksforGeeksarrow-up-right: “end element of smaller list is smaller than end elements of larger lists“.

record the tail table by keeping updating current value to correct position into the tail table 
through binary search
class Solution {
    public int lengthOfLIS(int[] nums) {
    int[] tails = new int[nums.length];
    int size = 0;
    for (int x : nums) {
        int i = 0, j = size;
        while (i != j) {
            int m = (i + j) / 2;
            if (tails[m] < x)
                i = m + 1;
            else
                j = m;
        }
        tails[i] = x;
        if (i == size) ++size;
    }   
    return size;
    }
}

using Arrays.binarySearch by jopiko123arrow-up-right:

Code Binary Search with O(nlogn) by dtccwlarrow-up-right, inspired by GeeksforGeeksarrow-up-right

Last updated

Was this helpful?