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]
, return3
For[4, 2, 4, 5, 3, 7]
, the LIS is[4, 4, 5, 7]
, return4
指针
因为是求最长的子序列,能够index不连续,能够考虑用DP解决。好比dp[i]
表示觉得i元素结尾的子序列的最大长度,那么能够根据全部dp[j]
(j < i)来获得dp[i]
的值。code
这道题也能够有简单的Follow up, 好比找index是连续的增长或减小的子序列最大长度。
因为index是连续,直接两个指针就能够解决,注意两种可能性,一种增大,一种减少。getExample
For[5, 4, 2, 1, 3]
, the LICS is[5, 4, 2, 1]
, return4
.
For[5, 1, 2, 3, 4]
, the LICS is[1, 2, 3, 4]
, return4
.it这道题与另一道题比较也比较相似,可参考Binary Tree Longest Consecutive Sequence。io
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; } }
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; } }