Longest Increasing Subsequence

Question

from lintcode

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

You code should return the length of the LIS.

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.

  • https://en.wikipedia.org/wiki/Longest_increasing_subsequence

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 [2, 4, 5, 7], return 4

Idea

N^2 time complexity. Compute LIS between the first element and each element afterwards (inclusively). Track the global maximum.

public class Solution {
    /**
     * @param nums: An integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        // f[i] means the length of LIS from nums[0] to nums[i]
        int[] f = new int[nums.length];
        int max = 0;
        // iterate each element
        for (int i = 0; i < nums.length; i++) {
            // start counting
            f[i] = 1;
            // iterate from zero-idx to previous element (current one counted at previous statement)
            for (int j = 0; j < i; j++) {
                // if that num smaller than current element
                if (nums[j] < nums[i]) {
                    // that means
                    // sequence from some-idx to that num
                    // is a subsequence of some-idex to current element
                    // so, we can try update the subsequence length maximum
                    f[i] = f[i] > f[j] + 1 ? f[i] : f[j] + 1;
                }
            }
            // update the global maximum
            if (f[i] > max) {
                max = f[i];
            }
        }
        return max;
    }
}

你可能感兴趣的:(Longest Increasing Subsequence)