Longest Increasing Subsequence

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

Example:

Input: [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. 

Note:

  • 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?

class Solution {
    // O(NlogN)
    public int lengthOfLIS(int[] nums) {
        // arr[i] -> Stores the smallest last digit in LIS of length i
        int[] arr = new int[nums.length];
        int ans = 0;
        for (int x : nums) {
            // Binary searching for the correct position of 'x'
            int start = 0, end = ans;
            while (start < end) {
                int mid = start + (end - start) / 2;
                if (arr[mid] < x)
                    start = mid + 1;
                else
                    end = mid;
            }
            arr[start] = x;
            if (start == ans)
                ans++;
        }
        return ans;
    }
    // O(N^2)
    public int lengthOfLIS(int[] nums) {
        if (nums.length == 0)
            return 0;
        int dp[] = new int[nums.length];
        dp[0] = 1;
        // dp[i] -> length of LIS upto this point(including this point)
        for (int i = 1; i < nums.length; i++) {
            dp[i] = 1;// base case
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) // For increasing subsequence
                    dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
        int max = 0;
        for (int x : dp)
            max = Math.max(x, max);
        return max;
    }
}

Last updated