题目描述
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)
样例
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]).
解
(LIS) $O(n\log{n})$
这个操作是从leetcode discuss上转来的(群里也有教学):
假设您先刷了DP1的LIS(第300题)。
首先,我们把原数组排序,按x升序,相同x下y降序排列。
于是input变成这样:[[2,3],[5,4],[6,7],[6,4]]
然后对y做lis就好了。原理是显然的。
example code(Python)
from bisect import bisect_left
class Solution:
def maxEnvelopes(self, envelopes):
tails = []
for _,h in sorted(envelopes, key = lambda env : (env[0], -env[1])):
pos = bisect_left(tails, h)
if pos == len(tails):
tails.append(h)
else:
tails[pos] = h
return len(tails)
哇 强啊!!!