[LintCode]Longest Increasing Subsequence

Longest Increasing Subsequence

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

You code should return the length of the LIS.spa

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

分析

因爲是求最長的子序列,能夠index不連續,能夠考慮用DP解決。好比dp[i]表示覺得i元素結尾的子序列的最大長度,那麼能夠根據全部dp[j](j < i)來獲得dp[i]的值。code

這道題也能夠有簡單的Follow up, 好比找index是連續的增長或減小的子序列最大長度。
因爲index是連續,直接兩個指針就能夠解決,注意兩種可能性,一種增大,一種減少。get

Example
For [5, 4, 2, 1, 3], the LICS is [5, 4, 2, 1], return 4.
For [5, 1, 2, 3, 4], the LICS is [1, 2, 3, 4], return 4.it

這道題與另一道題比較也比較相似,可參考Binary Tree Longest Consecutive Sequenceio

複雜度

time: O(n^2), space: O(n)class

代碼

public class Solution {
    public int longestIncreasingSubsequence(int[] nums) {
        if (nums.length == 0)
            return 0;
        int max = 0;
        int[] dp = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] >= nums[j]) // 必須是遞增
                    dp[i] = Math.max(dp[i], dp[j] + 1);
            }
            max = Math.max(max, dp[i]); // 更新全局最大值
        }
        return max;
    }
}

Follow up

time: O(n), space: O(n)im

public class Solution {
    public int longestIncreasingContinuousSubsequence(int[] A) {
        // Write your code here
        if (A == null || A.length == 0) {
            return 0;
        }
        int l = 0;
        int r = 1;
        int max = 1;
        while (r < A.length) {
            if (A[r] > A[r - 1]) {
                // 連續增長的狀況
                while (r < A.length && A[r] > A[r - 1]) {
                    r++;
                }
            } else {
                // 連續減少的狀況
                while (r < A.length && A[r] < A[r - 1]) {
                    r++;
                }
            }
            max = Math.max(max, r - l);
            l = r - 1;
        }
        return max;
    }
}
相關文章
相關標籤/搜索