[LeetCode] Russian Doll Envelopes

354. Russian Doll Envelopes

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

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.

Return the maximum number of envelopes can you Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
sort(envelopes.begin(), envelopes.end());
int res = 0, sz = envelopes.size();
vector<int> contain(sz, 0);
for(int i = 0; i < sz; i++) {
for(int j = 0; j < i; j++) {
if(envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1])
contain[i] = max(contain[i], contain[j]);
}
res = max(res, ++contain[i]);
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
unordered_map<int, unordered_set<int>> tree;
sort(envelopes.begin(), envelopes.end(), [](const vector<int>& v1, const vector<int>& v2) -> bool { return v1[0] == v2[0] ? v1[1] > v2[1] : v1[0] < v2[0]; });
int sz = envelopes.size();
vector<int> contain;
contain.push_back(INT_MIN);
for(int i = 0; i < sz; i++) {
if(contain.back() < envelopes[i][1])
contain.push_back(envelopes[i][1]);
else {
auto it = lower_bound(contain.begin(), contain.end(), envelopes[i][1]);
*it = envelopes[i][1];
}
}

return contain.size() - 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/30/PS/LeetCode/russian-doll-envelopes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.