300. Longest Increasing Subsequence
Medium
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input:[10,9,2,5,3,7,101,18]Output: 4 Explanation: The longest increasing subsequence is[2,3,7,101], therefore the length is4.
Note:
- There may be more than one LIS combination, it is only necessary for you to return the length.
- Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
Solutin:
1 initial a n length array dp(n). dp(i) means the length of LIS which ends at index i such that the last element of LIS is arr[i].
2 initail 1 for all indexs in dp.
3 dp[i] = dp[j] + 1 if dp[i] > dp[j] and i > j > 0;
4 to find the length of LIS, we should the max value of dp[i] (0<i<n).
public int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
for(int i = 0; i < n; i++){
dp[i] = 1;
}
for(int i = 1; i < n; i++){
for(int j = 0; j < i; j++){
if(nums[j] < nums[i]){
dp[i] = Math.max(dp[j] + 1,dp[i]);
}
}
}
int len = 0;
for(int i = 0; i < n; i++){
len = Math.max(dp[i],len);
}
return len;
}
related issue:
673. Number of Longest Increasing Subsequence
Building Brige
Comments
Post a Comment