Description
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]
, return3
For[4, 2, 4, 5, 3, 7]
, the LIS is[2, 4, 5, 7]
, return4
Solution
public class Solution {
/*
* @param nums: An integer array
* @return: The length of LIS (longest increasing subsequence)
*/
public int longestIncreasingSubsequence(int[] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
int[] dp = new int[n];
int max = 1;
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = i - 1; j >= 0; j--) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
max = Math.max(max, dp[i]);
}
return max;
}
}