Leetcode 354: Russian Doll Envelopes

dume0011
2 min readFeb 28, 2021

--

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]).

Problem Analysis:

The basic idea is sort the envelopes with width, and height by second, using dynamic programming to test the maximum number.

Solution 1:

class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (envelopes.size() == 0) return 0;

sort(envelopes.begin(), envelopes.end(), [](const vector<int>& lhs, const vector<int>& rhs) {
return lhs.front() < rhs.front() || (lhs.front() == rhs.front() && lhs.back() < rhs.back());
});
vector<int> dp(envelopes.size(), 1);
int res = 1;
for (int i = 1; i < dp.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1]) {
dp[i] = max(dp[i], dp[j] + 1);
res = max(dp[i], res);
}
}
}

return res;
}
};

As has sorted by width, we can update height to optimize in dynamic programming:

class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
int len = envelopes.size();
if (len == 0) return 0;
sort(envelopes.begin(), envelopes.end(),
[](pair<int, int>& a, pair<int, int>& b) {
return a.first < b.first || (a.first == b.first && a.second > b.second);
});
vector<int> dp;
for (auto &item: envelopes) {
auto search = lower_bound(dp.begin(), dp.end(), item.second);
if (search == dp.end()) dp.push_back(item.second);
else if (*search > item.second) *search = item.second;
}
return dp.size();
}
};

The two solutions’s space complexity are O(n), the first time complexity is O(n²), the second is O(nlgn)

--

--

No responses yet