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

{% hint style="info" %}
Dynamic programming算是brute force解。
{% endhint %}

```cpp
// Dynamic Programming
int maxEnvelopes(vector<vector<int>>& envelopes) { // time: O(n^2); space: O(n)
    if (envelopes.empty()) return 0;
    sort(envelopes.begin(), envelopes.end());
    int n = envelopes.size();
    // int res = 0;
    vector<int> len(n, 1);
    for (int i = 0; i < n; ++i) {
        for (int j = i - 1; j >= 0; --j) {
            if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1])
                len[i] = max(len[i], len[j] + 1);
        }
        // res = max(res, len[i]);
    }
    return *max_element(len.begin(), len.end());
}
```

{% hint style="info" %}
也可以利用先前在Longest Increasing Subsequence中用到的Binary Search來提昇效率到O(nlogn)。先把envelopes照寬度由小到大排序，如果寬度一樣，則照高度由大到小排序。這是因為這個演算法讓同一個寬度中保留最小的高度高於前一個寬度信封的高度。
{% endhint %}

```cpp
// Binary Search with lower_bound
int maxEnvelopes(vector<vector<int>>& envelopes) { // time: O(nlogn); space: O(n)
    if (envelopes.empty()) return 0;
    sort(envelopes.begin(), envelopes.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
    });
    vector<int> tmp; // only store heights
    for (auto& e : envelopes) {
        auto it = lower_bound(tmp.begin(), tmp.end(), e[1]); // find the first height not less than current height
        if (it == tmp.end()) tmp.push_back(e[1]);
        else if (*it > e[1]) *it = e[1];
    }
    return tmp.size();
}
```

```cpp
// Binary Search with lower_bound
int maxEnvelopes(vector<vector<int>>& envelopes) { // time: O(nlogn); space: O(n)
    if (envelopes.empty()) return 0;
    sort(envelopes.begin(), envelopes.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
    });
    vector<int> tmp; // only store heights
    int n = envelopes.size();
    for (int i = 0; i < n; ++i) {
        int l = 0, r = tmp.size();
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (tmp[mid] < envelopes[i][1]) l = mid + 1;
            else r = mid;
        }
        if (l == tmp.size()) tmp.push_back(envelopes[i][1]);
        else if (tmp[l] > envelopes[i][1]) tmp[l] = envelopes[i][1];
    }
    return tmp.size();
}
```

{% content-ref url="/pages/-La7f5efWfesNW0X--So" %}
[300. Longest Increasing Subsequence](/practice-of-algorithm-problems/dynamic-programming/300.-longest-increasing-subsequence.md)
{% endcontent-ref %}

{% content-ref url="/pages/-La7rYDyxLWCWrDzlAIt" %}
[673. Number of Longest Increasing Subsequence](/practice-of-algorithm-problems/dynamic-programming/673.-number-of-longest-increasing-subsequence.md)
{% endcontent-ref %}

{% content-ref url="/pages/-La7di8R98M0u4f9JK0d" %}
[674. Longest Continuous Increasing Subsequence](/practice-of-algorithm-problems/dynamic-programming/674.-longest-continuous-increasing-subsequence.md)
{% endcontent-ref %}


---

# 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://jimmylin1991.gitbook.io/practice-of-algorithm-problems/dynamic-programming/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.
