Description Link to heading
354. Russian Doll Envelopes (Hard)
Solution Link to heading
The initial reaction to this problem is definitely sorting. The question is, should the second dimension be sorted in ascending or descending order?
Firstly, let’s observe the question. It states that both dimensions must be strictly smaller. When I attempted the problem myself, I didn’t notice this point and got stuck for a while. However, once we consider this requirement, it becomes much clearer.
Let’s assume we sort in ascending order based on the second dimension. When we choose $(w_i, h_i)$, we need to find the maximum $(w_j, h_j)$ that satisfies both dimensions being strictly smaller than $(w_i, h_i)$. This connects to the Longest Increasing Subsequence (LIS) problem.
At this point, we realize that the second dimension should be sorted in descending order. By sorting in descending order, we can transform the problem into finding the LIS of the array composed of $h_i$ values.
If the second dimension is sorted in ascending order, both $(4, 5)$ and $(4, 6)$ would be included in the LIS, which doesn’t meet the requirements of the problem.
By sorting in descending order based on the second dimension, we can ensure that only one envelope with the same $w$ value is included in the LIS.
Code Link to heading
class Solution {
public:
int Bfind(vector<int> &lis, int target, vector<vector<int>> &envelopes, int right) {
int left = 0;
while (left < right) {
int mid = left + (right - left) / 2;
if (lis[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
int maxEnvelopes(vector<vector<int>> &envelopes) {
auto cmp = [](vector<int> &vec1, vector<int> &vec2) {
if (vec1[0] == vec2[0]) {
return vec1[1] >= vec2[1];
}
return vec1[0] < vec2[0];
};
sort(envelopes.begin(), envelopes.end(), cmp);
int n = envelopes.size(), ans = 0;
vector<int> lis(n);
for (int i = 0; i < n; ++i) {
int idx = Bfind(lis, envelopes[i][1], envelopes, ans);
if (idx >= ans) {
++ans;
}
lis[idx] = envelopes[i][1];
}
return ans;
}
};