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]).
classSolution {// O(NlogN) SolutionpublicintmaxEnvelopes(int[][] envelopes) {// Sort on basis of Side// Descending sort on unsorted sideArrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);// Now we can apply LIS on unsorted sideint dp[] =newint[envelopes.length];int ans =0;for (int[] envelope : envelopes) {// Searching for correct position of envelop in arrayint low =0, high = ans;while (low < high) {int mid = low + (high - low) /2;if (envelope[1] > dp[mid]) low = mid +1;else high = mid; } dp[low] = envelope[1];if (low == ans) ans++; }return ans; }// O(n^2) SolutionpublicintmaxEnvelopes(int[][] envelopes) {// Sort on basis of SideArrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);// Now we can apply LIS on unsorted sideint[] dp =newint[envelopes.length];int max =0;for (int i =0; i <envelopes.length; i++) {// Base case dp[i] =1;for (int j =0; j < i; j++) {if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1]) dp[i] =Math.max(dp[i], dp[j] +1); } max =Math.max(max, dp[i]); }return max; }}