Comment on page

# 354.Russian-Doll-Envelopes

## 题目描述

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)
class Solution {
public int maxEnvelopes(int[][] envelopes) {
Arrays.sort(envelopes, new Comparator<int[]>() {
public int compare(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 part
return 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 = new int[envelopes.length];
for (int i = 0; i < envelopes.length; i++) {
secondDim[i] = envelopes[i][1];
}
return lengthOfLIS(secondDim);
}
private int lengthOfLIS(int[] nums) {
int[] dp = new int[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;
}
}