Longest|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
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;
}
}
推荐阅读
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- python|leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
- Maximum|Maximum Subsequence Sum
- For|For many, life's longest mile is the stretch from dependence to independence
- [codeforces 1365E] Maximum Subsequence Value 或运算+为什么选三个元素对应最大值
- 动态规划|Longest Common Subsequence(入门dp题)
- Leetcode-549. Binary Tree Longest Consecutive Sequence II
- 32.|32. Longest Valid Parentheses
- 北大oj百练-1458:Common|北大oj百练-1458:Common Subsequence
- [Lintcode] Longest Increasing Subsequence 最长上升序列