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
Challenge
Time complexity O(n^2) or O(nlogn)
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_common_subsequence_problem
-------------------------- thinking ------------------------------
http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence.cpp
http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence
-------------------------- codes ----------------------------------
class Solution {
public:
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
int longestIncreasingSubsequence(vector<int> nums) {
if (nums.size() == 0) return 0;
// write your code here
vector<int> sub_max(nums.size(), 1);
for (int j = 1; j < nums.size(); j++) {
int index = j - 1;
while (index>=0) {
if (nums[index] <= nums[j] && (sub_max[index] + 1 > sub_max[j])) {
sub_max[j] = sub_max[index] + 1;
}
index--;
}
}
int max = 1;
for (int i = 1; i < sub_max.size(); i++) {
if (sub_max[i] > max) {
max = sub_max[i];
}
}
return max;
}
};
No comments:
Post a Comment