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.

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 <= 5000
envelopes[i].length == 2
1 <= wi, hi <= 104

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import bisect
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
if not envelopes:
return 0
envelopes.sort(key=lambda x: (x[0], -x[1]))
size = 0
res = [0]*len(envelopes)
for w, h in envelopes:
l, r = 0, size -1
while l <= r:
mid = (l+r) // 2
if res[mid] >= h:
r = mid - 1
else:
l = mid + 1
res[l] = h
size = max(size, l+1)
return size

references

Commentaires

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×