354-Russian-Doll-Envelopes
Last updated
Last updated
class Solution {
public int maxEnvelopes(int[][] envelopes) {
if(envelopes==null || envelopes.length==0){
return 0;
}
Arrays.sort(envelopes,new Comparator<int[]>(){
@Override
public int compare(int[] lhs,int[] rhs){
return lhs[0]-rhs[0];
}
});
int[] dp=new int[envelopes.length];
dp[0]=1;
int result=1;
for(int i=1;i<envelopes.length;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(envelopes[i][0]>envelopes[j][0] && envelopes[i][1]>envelopes[j][1]){
dp[i]=Math.max(dp[i],dp[j]+1);
}
}
result=Math.max(result,dp[i]);
}
return result;
}
}class Solution {
public int maxEnvelopes(int[][] envelopes) {
if(envelopes==null || envelopes.length==0){
return 0;
}
Arrays.sort(envelopes,new Comparator<int[]>(){
@Override
public int compare(int[] lhs,int[] rhs){
return lhs[0]==rhs[0]?rhs[1]-lhs[1]:lhs[0]-rhs[0];
}
});
int count=0;
int[][] buckets=new int[envelopes.length][2];
for(int i=0;i<envelopes.length;i++){
int left=0;
int right=count;
while(left<right){
int mid=left+(right-left)/2;
if(buckets[mid][1]>=envelopes[i][1]){
right=mid;
}else{
left=mid+1;
}
}
buckets[left]=envelopes[i];
if(left==count){
count++;
}
}
return count;
}
}