<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 {
public:
    int getMax(int idx, int si, int st, int qi, int qt, vector<int>& arr){
        if(si>=qi && st<=qt)
            return arr[idx];
        if(si>qt || st<qi)
            return 0;
        int mid=(si+st)/2;
        return max(getMax(2*idx+1, si, mid, qi,qt, arr), getMax(2*idx+2, mid+1, st, qi, qt, arr));
    }
    void update(int idx, int si, int st, int val,int kk, vector<int>& arr){
        if(val>st || val<si)
            return;
        arr[idx]=max(kk,arr[idx]);
        if(si!=st){
            int mid=(si+st)/2;
            update(2*idx+1, si, mid, val,kk, arr);
            update(2*idx+2, mid+1, st, val,kk, arr);
        }
    }
    int maxEnvelopes(vector<vector<int>>& en) {
        sort(en.begin(), en.end());
        vector<int> arr(400004,0);
        int maxs=0;
        int idx=0;
        while(idx<(int)en.size()){
            // cout<<en[idx][0]<<"=="<<en[idx][1]<<"\n";
            int tt=idx;
            vector<pair<int,int>> trr;
            while(tt<en.size() && en[tt][0]==en[idx][0]){
                int bb=getMax(0, 0, 100001, 0, en[tt][1]-1, arr)+1;
                trr.push_back(make_pair(en[tt][1], bb));
                maxs=max(maxs, bb);
                tt++;
            }
            for(int k=idx;k<tt;k++)
                update(0, 0, 100001, trr[k-idx].first, trr[k-idx].second, arr);
            idx=tt;
        }
        return maxs;
    }
};
190153