Algorithm
Problem Name: 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 are greater than the other envelope's width and height.
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Example 1:
Input: envelopes = [[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]).
Example 2:
Input: envelopes = [[1,1],[1,1],[1,1]] Output: 1
Constraints:
1 <= envelopes.length <= 105
envelopes[i].length == 2
1 <= wi, hi <= 105
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
sort(envelopes.begin(), envelopes.end(), [](pair < int, int>& p1, pair<int, int>& p2){
return p1.first == p2.first ? p1.second > p2.second : p1.first < p2.first;
});
vector<int>dp;
for(auto x: envelopes){
int pos = lower_bound(dp.begin(), dp.end(), x.second) - dp.begin();
if(pos == dp.size()) dp.push_back(x.second);
else dp[pos] = x.second;
}
return dp.size();
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const maxEnvelopes = function(envelopes) {
const env = envelopes
env.sort((a, b) => a[0] - b[0] || b[1] - a[1])
const stk = []
for(const e of env) {
if(stk.length === 0 || e[1] > stk[stk.length - 1][1]) {
stk.push(e)
continue
}
let l = 0, r = stk.length - 1
while(l < r) {
const mid = l + Math.floor((r - l) / 2)
if(stk[mid][1] < e[1]> l = mid + 1
else r = mid
}
stk[l] = e
}
return stk.length
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def maxEnvelopes(self, envelopes):
tails = []
for w, h in sorted(envelopes, key = lambda x: (x[0], -x[1])):
i = bisect.bisect_left(tails, h)
if i == len(tails): tails.append(h)
else: tails[i] = h
return len(tails)
Copy The Code &
Try With Live Editor
Input
Output