# 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.

Example:

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]).

# Solution

Essentially 300. Longest Increasing Subsequence in 2D.

Approach 1: DP -- sort the envelopes first by width, then by height. O(N^2).

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. O(NlogN).

# Code (Python)

Approach 1:

    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][0] < envelopes[i][0] and envelopes[j][1] < envelopes[i][1]:
                    max_envelopes[i] = max(max_envelopes[i], max_envelopes[j] + 1)
        return max(max_envelopes)

Approach 2:

    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[0], -pair[1]))
        # 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[0][1]]
        for i in range(1, len(envelopes)):
            left, right = 0, len(heights_taken)
            while left < right:
                mid = (left + right) // 2
                if envelopes[i][1] <= heights_taken[mid]:
                    right = mid
                else:
                    left = mid + 1
            if left == len(heights_taken):
                heights_taken.append(envelopes[i][1])
            else:
                heights_taken[left] = envelopes[i][1]
        return len(heights_taken)

# Code (C++)

Approach 1:

Approach 2: