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

```java
class Solution {
    // O(NlogN) Solution
    public int maxEnvelopes(int[][] envelopes) {
        // Sort on basis of Side
        // Descending sort on unsorted side
        Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
        // Now we can apply LIS on unsorted side
        int dp[] = new int[envelopes.length];
        int ans = 0;
        for (int[] envelope : envelopes) {
            // Searching for correct position of envelop in array
            int low = 0, high = ans;
            while (low < high) {
                int mid = low + (high - low) / 2;
                if (envelope[1] > dp[mid])
                    low = mid + 1;
                else
                    high = mid;
            }
            dp[low] = envelope[1];
            if (low == ans)
                ans++;
        }
        return ans;
    }

    // O(n^2) Solution
    public int maxEnvelopes(int[][] envelopes) {
        // Sort on basis of Side
        Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
        // Now we can apply LIS on unsorted side
        int[] dp = new int[envelopes.length];
        int max = 0;
        for (int i = 0; i < envelopes.length; i++) {
            // Base case
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1])
                    dp[i] = Math.max(dp[i], dp[j] + 1);
            }
            max = Math.max(max, dp[i]);
        }
        return max;
    }
}
```


---

# 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://mayanktyagi3111.gitbook.io/interview-prep/dynamic-programming/untitled-3.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.
