One, Title Description
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.
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]).
Second, the problem solution
Method One: dp
In fact, this is one of the longest sequence of deformation rising child, think about if a certain property of the envelope is ascending, the size of the other attributes of discrimination can be converted into a one-dimensional problem of the dp.
public int maxEnvelopes(int[][] enves) {
int N = enves.length;
if (N == 0) return 0;
Arrays.sort(enves, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] == b[0]) {
return b[1] - a[1];
}
return a[0] - b[0];
}
});
int[] dp = new int[N];
Arrays.fill(dp, 1);
int max = 1;
for (int i = 1; i < N; i++) {
for (int j = 0; j < i; j++)
if ( enves[j][1] < enves[i][1])
dp[i] = Math.max(dp[i], dp[j] + 1);
if (dp[i] > max)
max = dp[i];
}
return max;
}
Complexity Analysis
- time complexity: ,
- Space complexity: ,
Method two: two minutes (to be done)
Complexity Analysis
- time complexity: ,
- Space complexity: ,