<p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p>

<p>One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope&#39;s width and height.</p>

<p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p>

<p><strong>Note:</strong> You cannot rotate an envelope.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]).
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li>
	<li><code>envelopes[i].length == 2</code></li>
	<li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution {
    class seg {
        vector<int> t;
        const int n;
        public:
        seg(int n) : n(n) {
            t = vector<int>(n << 1, 0);
        }

        int query(int l, int r) {
            int res = 0;
            for (l += n, r += n; l < r; l>>=1, r>>=1) {
                if (l % 2) res = max(res, t[l++]);
                if (r % 2) res = max(res, t[--r]);
            }
            return res;
        }

        void update(int i, int val) {
            for (i += n; i; i>>=1) {
                t[i] = max(t[i], val);
            }
        }
    };
public:
    int maxEnvelopes(const vector<vector<int>>& env) {
        map<int, vector<int>> mp;
        for (const auto v : env) {
            mp[v[0]].push_back(v[1]);
        }

        seg st((int)1e5 + 1);

        int res = 1;
        for (const auto& [_, v] : mp) {
            vector<int> r;
            r.reserve(v.size());
            for (const auto x : v) {
                r.push_back(1 + st.query(0, x));
            }

            for (int i = 0; i < r.size(); ++i) {
                st.update(v[i], r[i]);
                cout << r[i] << endl;
                res = max(res, r[i]);
            }
        }
        return res;
    }
};
164559