Give you a two-dimensional integer array envelopes, where envelopes[i] = [wi, hi], representing the width and height of the i-th envelope.
When the width and height of another envelope are larger than this envelope, this envelope can be put into another envelope, just like a Russian doll.
Please calculate the maximum number of envelopes that can form a set of "Russian doll" envelopes (that is, you can put one envelope into another envelope).
Note: Rotating envelopes is not allowed.
Example 1:
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes is 3, the combination is: [2,3] => [5,4] => [6,7].
Example 2:
Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1
prompt:
1 <= envelopes.length <= 5000
envelopes[i].length == 2
1 <= wi, hi <= 104
代码:
public int maxEnvelopes(int[][] envelopes) {
//按照每个信封的宽度进行升序排列,若宽度一样,则按高度降序排列
//Arrays.sort(envelopes,(a,b)->a[0]==b[0]?b[1]-a[1]:a[0]-b[0]);;
Arrays.sort(envelopes, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0];
}
});
int [] a=new int[envelopes.length];
//查找以a[i]结尾的最长递增子序列的长度
for(int i=0;i<envelopes.length;i++) {
a[i]=envelopes[i][1];
}
return maxLength(a);
}
public int maxLength(int[] envelopes) {
//以a[i]结尾的最长递增子序列的长度
int [] a=new int[envelopes.length];
Arrays.fill(a,1);
for(int i=0;i<envelopes.length;i++) {
for(int j=0;j<i;j++) {
if(envelopes[j]<envelopes[i]) {
a[i]=Math.max(a[j]+1,a[i]);
}
}
}
int max=0;
for(int i=0;i<envelopes.length;i++) {
max=Math.max(max,a[i]);
}
return max;
}