[LintCode]Longest Increasing Subsequence

Longest Increasing Subsequence

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

You code should return the length of the LIS.

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]的值。

这道题也可以有简单的Follow up, 比如找index是连续的增加或减少的子序列最大长度。
由于index是连续,直接两个指针就可以解决,注意两种可能性,一种增大,一种减小。

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.

这道题与另外一道题比较也比较类似,可参考Binary Tree Longest Consecutive Sequence

复杂度

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

代码

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)

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值