Longest Increasing Subsequence

2018-04-13  本文已影响0人  Star_C

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?

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;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读