You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Note:
Rotation is not allowed.
Example:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
代码
Approach #1 Sort + Longest Increasing Subsequence
Time: O(N log N) && Space: O(N)
classSolution {publicintmaxEnvelopes(int[][] envelopes) {Arrays.sort(envelopes,newComparator<int[]>() {publicintcompare(int[] arr1,int[] arr2) {if (arr1[0] == arr2[0]) { // we also sort decreasing on the second dimension, so two envelopes that are equal in the first dimension can never be in the same increasing subsequence
this is the key partreturn arr2[1] - arr1[1]; // 当w相同,h降序 } else {return arr1[0] - arr2[0]; } } });// Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);int[] secondDim =newint[envelopes.length];for (int i =0; i <envelopes.length; i++) { secondDim[i] = envelopes[i][1]; }returnlengthOfLIS(secondDim); }privateintlengthOfLIS(int[] nums) {int[] dp =newint[nums.length];int len =0;for (int num: nums) {int i =Arrays.binarySearch(dp,0, len, num);if (i <0) { i =- (i +1); } dp[i] = num;if (i == len) { len++; } }return len; }}