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]).
这个问题相当于Longest Increasing Subsequence的二维版本
思路就是固定一个维度,对另外一个维度求Longest Increasing Subsequence
使用dp来做会有个别case超时
LIS中如果新找的数比所有a中的数都大,append到a中。否则把a中对应的index位置更新为num
逻辑是做更新的这一步,更新为了更小的值,使得后续能加入的更多了。
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
a = []
for num in nums:
idx = bisect.bisect_left(a, num)
if idx == len(a):
a.append(num)
else:
a[idx] = num
return len(a)
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key = lambda x: (x[0], -x[1]))
#reduce to 1D
height = [y for _,y in envelopes]
return self.lengthOfLIS(height)