Skip to content

Commit b46b04c

Browse files
committed
Add solution #354
1 parent 1547fdc commit b46b04c

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,7 @@
283283
349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy|
284284
350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy|
285285
352|[Data Stream as Disjoint Intervals](./0352-data-stream-as-disjoint-intervals.js)|Hard|
286+
354|[Russian Doll Envelopes](./0354-russian-doll-envelopes.js)|Hard|
286287
355|[Design Twitter](./0355-design-twitter.js)|Medium|
287288
367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy|
288289
371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 354. Russian Doll Envelopes
3+
* https://leetcode.com/problems/russian-doll-envelopes/
4+
* Difficulty: Hard
5+
*
6+
* You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents
7+
* the width and the height of an envelope.
8+
*
9+
* One envelope can fit into another if and only if both the width and height of one envelope
10+
* are greater than the other envelope's width and height.
11+
*
12+
* Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
13+
*
14+
* Note: You cannot rotate an envelope.
15+
*/
16+
17+
/**
18+
* @param {number[][]} envelopes
19+
* @return {number}
20+
*/
21+
var maxEnvelopes = function(envelopes) {
22+
const result = [];
23+
24+
envelopes.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]);
25+
envelopes.forEach(([_, h]) => {
26+
let left = 0;
27+
let right = result.length;
28+
while (left < right) {
29+
const middle = Math.floor((left + right) / 2);
30+
if (result[middle] >= h) {
31+
right = middle;
32+
} else {
33+
left = middle + 1;
34+
}
35+
}
36+
if (left === result.length) {
37+
result.push(h);
38+
} else {
39+
result[left] = h;
40+
}
41+
});
42+
43+
return result.length;
44+
};

0 commit comments

Comments
 (0)