# 354.Russian-Doll-Envelopes

## 354. Russian Doll Envelopes

## 题目地址

<https://leetcode.com/problems/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]).
```

## 代码

### Approach #1 Sort + Longest Increasing Subsequence

Time: O(N log N) && Space: O(N)

```java
class Solution {

  public int maxEnvelopes(int[][] envelopes) {
        Arrays.sort(envelopes, new Comparator<int[]>() {
      public int compare(int[] arr1, int[] arr2) {
        if (arr1[0] == arr2[0]) {
          // we also sort decreasing on the second dimension, so two envelopes that are equal in the first dimension can never be in the same increasing subsequence
this is the key part
          return arr2[1] - arr1[1]; // 当w相同，h降序
        } else {
          return arr1[0] - arr2[0];
        }
      }
    });

   // Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);

    int[] secondDim = new int[envelopes.length];
    for (int i = 0; i < envelopes.length; i++) {
      secondDim[i] = envelopes[i][1];
    }
    return lengthOfLIS(secondDim);
  }

  private int lengthOfLIS(int[] nums) {
    int[] dp = new int[nums.length];
    int len = 0;
    for (int num: nums) {
      int i = Arrays.binarySearch(dp, 0, len, num);

      if (i < 0) {
        i = - (i + 1);
      }

      dp[i] = num;
      if (i == len) {
        len++;
      }
    }
    return len;
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/array/354.russian-doll-envelopes.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
