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)
Example: Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
Solution
public class Solution {
public int maxEnvelopes(int[][] envelopes) {
if (envelopes == null || envelopes.length == 0) return 0;
if (envelopes.length == 1) return 1;
List<Entity> list = new ArrayList<>();
for (int i = 0; i < envelopes.length; i++) {
list.add(new Entity(envelopes[i][0], envelopes[i][1]));
}
Collections.sort(list, (m, n) -> {
if (m.w < n.w) {
return -1;
} else if (m.w > n.w) {
return 1;
} else {
if (m.h < n.h) {
return -1;
} else if (m.h > n.h) {
return 1;
} else {
return 0;
}
}
});
int size = envelopes.length;
int[] dp = new int[size];
for(int i = 0; i < size; i ++) {
dp[i] = 1;
}
for(int i = 0; i < size; i ++) {
Entity ith = list.get(i);
for(int j = 0; j < i; j ++) {
Entity jth = list.get(j);
if (ith.h > jth.h && ith.w > jth.w) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
int result = 1;
for(int i = 0; i < size; i ++) {
result = Math.max(result, dp[i]);
}
return result;
}
private static class Entity {
int w;
int h;
public Entity(int w, int h) {
this.w = w;
this.h = h;
}
}
}