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?

Solution1:

  • Time complexity: O(n^2).
  • Space Complexity: O(n)
public int lengthOfLIS(int[] nums) {
    if (nums == null || nums.length == 0) return 0;

    int[] sizes = new int[nums.length]; // size array to keep track of the LIS ending with current location 
    String[] path = new String[nums.length]; // path array to keep the LIS

    for (int i = 0; i < nums.length; i++) {
        sizes[i] = 1;
        path[i] = nums[i] + " "; 
    }

    int maxLength = 1;
    for (int i = 1; i < nums.length; i++) {
        for (int j = 0; j < i; j++) { // when do we append our current value to the previous result?
        // only when the current number is smaller and sizes[i] < sizes[j] + 1 
            if (nums[j] < nums[i] && sizes[i] < sizes[j] + 1 ) { 
                sizes[i] = sizes[j] + 1;
                path[i] = path[j] + nums[i] + " ";
                maxLength = Math.max(maxLength, sizes[i]);
            }
        }
    }

    return maxLength;
}