# 354. Russian Doll Envelopes
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)
Note: Rotation is not allowed.
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]).
Essentially 300. Longest Increasing Subsequence in 2D.
Approach 1: DP -- sort the envelopes first by width, then by height.
Approach 2: Greedy + binary search -- sort first by width (small -> large), then by height (large -> small), then find longest increasing subsequence with the height values.
# Code (Python)
def maxEnvelopes(self, envelopes: List[List[int]]) -> int: if not envelopes: return 0 envelopes = sorted(envelopes) # first by width, then by height max_envelopes = [1 for _ in range(len(envelopes))] for i in range(1, len(envelopes)): for j in range(i): if envelopes[j] < envelopes[i] and envelopes[j] < envelopes[i]: max_envelopes[i] = max(max_envelopes[i], max_envelopes[j] + 1) return max(max_envelopes)
def maxEnvelopes(self, envelopes: List[List[int]]) -> int: if not envelopes: return 0 # sort first by width (small -> large), then by height (large -> small) envelopes = sorted(envelopes, key=lambda pair: (pair, -pair)) # now that height is periodically descreasing (e.g. 4,3,2, 4,3,2, 5,4,3,2), find the longest increasing subsequence -- take at most 1 envolope from each "group"/width heights_taken = [envelopes] for i in range(1, len(envelopes)): left, right = 0, len(heights_taken) while left < right: mid = (left + right) // 2 if envelopes[i] <= heights_taken[mid]: right = mid else: left = mid + 1 if left == len(heights_taken): heights_taken.append(envelopes[i]) else: heights_taken[left] = envelopes[i] return len(heights_taken)
# Code (C++)